use std::borrow::Cow;

use quick_xml::{events::attributes::Attribute, name::QName};

use super::WriteElement;

/// [feComposite](https://www.w3.org/TR/SVG11/filters.html#feCompositeElement)
#[derive(Debug)]
pub struct Composite {
    operator: CompositeOperator,
}

impl Composite {
    pub fn new(op: CompositeOperator) -> Self {
        Self { operator: op }
    }

    pub fn arithmetic(k1: f32, k2: f32, k3: f32, k4: f32) -> Self {
        Self {
            operator: CompositeOperator::Arithmetic { k1, k2, k3, k4 },
        }
    }
}

#[derive(Debug)]
pub enum CompositeOperator {
    Over,
    In,
    Out,
    Atop,
    Xor,
    Arithmetic { k1: f32, k2: f32, k3: f32, k4: f32 },
}

impl WriteElement for Composite {
    fn attrs(&self) -> Vec<quick_xml::events::attributes::Attribute> {
        let (op_name, vals) = match self.operator {
            CompositeOperator::Over => ("over", None),
            CompositeOperator::In => ("in", None),
            CompositeOperator::Out => ("out", None),
            CompositeOperator::Atop => ("atop", None),
            CompositeOperator::Xor => ("xor", None),
            CompositeOperator::Arithmetic { k1, k2, k3, k4 } => {
                ("arithmetic", Some([k1, k2, k3, k4]))
            }
        };

        let mut r = vec![Attribute {
            key: QName(b"operator"),
            value: Cow::from(op_name.as_bytes()),
        }];

        if let Some([k1, k2, k3, k4]) = vals {
            // r.append(&mut vec![
            //     Attribute {
            //         key: QName(b"k1"),
            //         value: Cow::from(k1.to_string().into_bytes()),
            //     },
            //     Attribute {
            //         key: QName(b"k2"),
            //         value: Cow::from(k2.to_string().into_bytes()),
            //     },
            //     Attribute {
            //         key: QName(b"k3"),
            //         value: Cow::from(k3.to_string().into_bytes()),
            //     },
            //     Attribute {
            //         key: QName(b"k4"),
            //         value: Cow::from(k4.to_string().into_bytes()),
            //     },
            // ]);
            r.append(&mut gen_attrs![
                b"k1": k1,
                b"k2": k2,
                b"k3": k3,
                b"k4": k4
            ]);
        }

        r
    }

    fn tag_name(&self) -> &'static str {
        "feComposite"
    }
}
