use brisk_it::generator::{Generator, Result};

#[derive(Default)]
pub(super) struct FileDialog {}

impl Generator for FileDialog {
    fn generate(
        &self,
        input: brisk_it::component::ComponentInput,
        _manager: &brisk_it::generator::Manager,
    ) -> Result<proc_macro2::TokenStream> {
        let mut modifiers = Vec::<proc_macro2::TokenStream>::new();
        let mut filters = quote::quote! {
            |x: rfd::FileDialog| { x }
        };

        let var = crate::utils::component_variable(&input);

        for prop in input.properties {
            if prop.name == "filters" {
                let expr = prop.expr;
                filters = quote::quote! {
                    |x: rfd::FileDialog| {
                        let mut x = x;
                        for (n,f) in #expr
                        {
                            x = x.add_filter(n, &f);
                        }
                        x
                    }
                };
            } else if prop.name == "directory" {
                let expr = prop.expr;
                modifiers.push(quote::quote! {
                    .set_directory(#expr)
                });
            } else if prop.name == "file_name" {
                let expr = prop.expr;
                modifiers.push(quote::quote! {
                    .set_file_name(#expr)
                });
            } else if prop.name == "title" {
                let expr = prop.expr;
                modifiers.push(quote::quote! {
                    .set_title(#expr)
                });
            } else if prop.name == "can_create_directories" {
                let expr = prop.expr;
                modifiers.push(quote::quote! {
                    .set_can_create_directories(#expr)
                });
            } else {
                return Err(brisk_it::errors::unknown_property(prop));
            }
        }

        Ok(quote::quote! {
            let #var = (#filters)(rfd::FileDialog::new()#(#modifiers)*);
        })
    }
    fn boxed_clone(&self) -> Box<dyn Generator> {
        Box::new(Self {})
    }
}
