use crate::generator;
use rsass::compile_scss_path;
use rsass::output::{Format, Style};
use std::io::Write;

const CHARSET: &'static str = r#"@charset "UTF-8";"#;

pub fn generate() -> anyhow::Result<()> {
    let format = Format {
        style: if cfg!(debug_assertions) {
            Style::Expanded
        } else {
            Style::Compressed
        },
        precision: 3,
    };

    let main = compile_scss_path(&generator::content_path("css/main.scss"), format)?;

    // strip the charset, it will be added to actually output files in generate_theme
    let main_slice: &[u8];
    let charset_bytes = CHARSET.as_bytes();
    if main.starts_with(charset_bytes) {
        main_slice = &main[charset_bytes.len()..];
    } else {
        main_slice = &main;
    }

    generate_theme("auto", format, main_slice)?;
    generate_theme("light", format, main_slice)?;
    generate_theme("dark", format, main_slice)?;

    Ok(())
}

fn generate_theme(name: &'static str, format: Format, main: &[u8]) -> anyhow::Result<()> {
    let res = compile_scss_path(
        &generator::content_path(format!("css/{}.scss", name)),
        format,
    )?;
    let mut writer =
        generator::util::output_writer(format!("css/{}.css", name)).expect("output writer");
    write!(writer, "{}\n", CHARSET).unwrap();
    writer.write_all(&res).expect("writing theme css");
    writer.write_all(main).expect("writing main");

    Ok(())
}
