mod check;

use clap::{command, Parser};
use easy_signed_distance_field as sdf;
use std::fs::{self, create_dir_all, File};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};

static TOTAL_GLYPHS_RENDERED: AtomicUsize = AtomicUsize::new(0);
const CHARACTERS: &'static str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ\
                  abcdefghijklmnopqrstuvwxyz\
                  0123456789\
                  ,.!?@#$%^&*()";

#[derive(Parser, Debug)]
#[command(version, author, about)]
struct Args {
    /// Sets the source directory to be scanned for fonts.
    font_dir: PathBuf,
    // / Sets the output directory in which the PBF glyphs will be placed (each font will be placed in a new subdirectory with appropriately named PBF files).
    // out_dir: PathBuf,
}

fn render_worker(path: &PathBuf, output: &PathBuf) {
    let mut file = fs::read(path).unwrap();
    let font = sdf::Font::from_bytes(file.as_slice(), Default::default()).unwrap();
    let px = 64.0;
    let padding = 2;
    let spread = 6.0;

    for c in CHARACTERS.chars() {
        if let Some((metrics, glyph_sdf)) = font.sdf_generate(px, padding, spread, c) {
            let mut output = output.join(format!("{}.png", c));
            output.parent().map(|p| create_dir_all(p).unwrap());
            sdf::sdf_to_file(output.as_os_str().to_str().unwrap(), &glyph_sdf).unwrap();
            output.set_file_name(format!("fuck_{}.png", c));
            sdf::sdf_render_to_file(
                output.as_os_str().to_str().unwrap(),
                0.5,
                0.5,
                0.02,
                &glyph_sdf,
            )
            .unwrap();
        }
    }
}

fn main() {
    let args = Args::parse();

    let font_dir = &args.font_dir;

    let num_threads = num_cpus::get();
    println!("Starting {num_threads} worker threads...");

    for dir_entry in font_dir
        .read_dir()
        .expect("Unable to open font directory")
        .flatten()
    {
        let path = dir_entry.path();

        if let (Some(stem), Some(extension)) = (path.file_stem(), path.extension()) {
            if path.is_file() && (["otf", "ttf"].contains(&extension.to_str().unwrap())) {
                println!("Rendering glyphs for font: {}", path.to_str().unwrap());
                let filename = PathBuf::from(format!("test/{}", stem.to_str().unwrap()));
                render_worker(&path, &filename)
            }
        }
    }
}
