// r8r: rust port of n8n.io
// Initial author: Michael Cochran <mcochran@cochranblock.org>
// Built for: Tanner Woodrum, intended cofounder
// License: Unlicense (public domain dedication, see UNLICENSE)
//
// `compression` — gzip / deflate compress/decompress. Input is a string;
// output is a base64-encoded blob (compress) or the decoded string
// (decompress).

use async_trait::async_trait;
use crate::core::error::NodeError;
use crate::core::types::*;
use crate::engine::{ExecuteCtx, Node, NodeFactory};
use base64::Engine as _;
use flate2::read::{GzDecoder, ZlibDecoder};
use flate2::write::{GzEncoder, ZlibEncoder};
use flate2::Compression;
use serde_json::Value;
use std::io::{Read, Write};
use std::sync::Arc;

pub struct CompressionNode;

static META: NodeMetadata = NodeMetadata {
    name: "compression",
    display_name: "Compression",
    version: &[1],
    group: &["transform"],
    description: "gzip/deflate compress and decompress strings",
    inputs: 1,
    outputs: 1,
    properties: &[],
    credentials: &[],
};

#[async_trait]
impl Node for CompressionNode {
    fn metadata(&self) -> &'static NodeMetadata { &META }

    async fn execute(&self, ctx: &mut ExecuteCtx<'_>) -> Result<NodeOutput, NodeError> {
        let op = ctx.node_def.parameters.get("operation")
            .and_then(|v| v.as_str()).unwrap_or("compress").to_string();
        let algorithm = ctx.node_def.parameters.get("algorithm")
            .and_then(|v| v.as_str()).unwrap_or("gzip").to_string();
        let field = ctx.node_def.parameters.get("output_field")
            .and_then(|v| v.as_str()).unwrap_or("output").to_string();

        let items_in = if ctx.input.is_empty() { vec![NodeItem::default()] } else { ctx.input.clone() };
        let mut out = Vec::with_capacity(items_in.len());
        for item in items_in {
            let value = ctx.param_str("value").unwrap_or_default();
            let result = match op.as_str() {
                "compress" => {
                    let bytes = match algorithm.as_str() {
                        "gzip" => {
                            let mut e = GzEncoder::new(Vec::new(), Compression::default());
                            e.write_all(value.as_bytes()).map_err(|e| NodeError::Other(format!("compression: {}", e)))?;
                            e.finish().map_err(|e| NodeError::Other(format!("compression: {}", e)))?
                        }
                        "deflate" => {
                            let mut e = ZlibEncoder::new(Vec::new(), Compression::default());
                            e.write_all(value.as_bytes()).map_err(|e| NodeError::Other(format!("compression: {}", e)))?;
                            e.finish().map_err(|e| NodeError::Other(format!("compression: {}", e)))?
                        }
                        other => return Err(NodeError::Other(format!("compression: unknown algorithm `{}`", other))),
                    };
                    Value::String(base64::engine::general_purpose::STANDARD.encode(bytes))
                }
                "decompress" => {
                    let bytes = base64::engine::general_purpose::STANDARD.decode(value.as_bytes())
                        .map_err(|e| NodeError::Other(format!("compression: base64: {}", e)))?;
                    let decoded = match algorithm.as_str() {
                        "gzip" => {
                            let mut d = GzDecoder::new(&bytes[..]);
                            let mut s = String::new();
                            d.read_to_string(&mut s).map_err(|e| NodeError::Other(format!("compression: {}", e)))?;
                            s
                        }
                        "deflate" => {
                            let mut d = ZlibDecoder::new(&bytes[..]);
                            let mut s = String::new();
                            d.read_to_string(&mut s).map_err(|e| NodeError::Other(format!("compression: {}", e)))?;
                            s
                        }
                        other => return Err(NodeError::Other(format!("compression: unknown algorithm `{}`", other))),
                    };
                    Value::String(decoded)
                }
                other => return Err(NodeError::Other(format!("compression: unknown operation `{}`", other))),
            };
            let mut new_json = if item.json.is_object() { item.json.clone() } else { Value::Object(Default::default()) };
            new_json.as_object_mut().unwrap().insert(field.clone(), result);
            out.push(NodeItem { json: new_json, ..item });
        }
        Ok(vec![out])
    }
}

inventory::submit! { NodeFactory::new("compression", || Arc::new(CompressionNode)) }
