use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub struct OxipngOptions {
    level: u8,
    strip_all: bool,
    alpha: bool,
}

#[wasm_bindgen]
impl OxipngOptions {
    #[wasm_bindgen(constructor)]
    pub fn new() -> OxipngOptions {
        Self {
            level: 2,
            strip_all: false,
            alpha: false,
        }
    }

    #[wasm_bindgen(setter)]
    pub fn set_level(&mut self, level: u8) {
        self.level = level.min(6);
    }

    #[wasm_bindgen(setter)]
    pub fn set_strip_all(&mut self, v: bool) {
        self.strip_all = v;
    }

    #[wasm_bindgen(setter)]
    pub fn set_alpha(&mut self, v: bool) {
        self.alpha = v;
    }
}

#[wasm_bindgen]
pub fn optimize(data: &[u8], opts: &OxipngOptions) -> Result<Vec<u8>, JsValue> {
    let mut options = oxipng::Options::from_preset(opts.level);
    options.optimize_alpha = opts.alpha;
    options.strip = if opts.strip_all {
        oxipng::StripChunks::All
    } else {
        oxipng::StripChunks::Safe
    };

    oxipng::optimize_from_memory(data, &options)
        .map_err(|e| JsValue::from_str(&e.to_string()))
}
