// This file is part of AllMyToes.
//
// AllMyToes is free software: you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any later version.
//
// AllMyToes is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with AllMyToes.
// If not, see <https://www.gnu.org/licenses/>.
//
//mod allmytoes;

use allmytoes::{get_thumbnail, ThumbSize};
use clap::Parser;
#[macro_use]
extern crate log;

#[derive(Parser)]
#[clap(author, version)]
#[clap(about = "Provides paths to image thumbnails and creates them if necessary, using the thumbnail database standardized by freedesktop.org", long_about = None)]
struct Cli {
    #[clap(short, long, help = "Enable debug output (on stderr)")]
    debug: bool,
    #[clap(short, long, value_parser = parse_toe_size, help="Thumbnail size (one of {n,l,x,xx}). Default: l (large)")]
    size: Option<ThumbSize>,
    #[clap(value_parser, help = "File for which a thumbnail shall be returned")]
    file: String,
    #[clap(long, help = "Force creation of thumbs no matter if they exist")]
    force_creation: bool,
}

fn parse_toe_size(s: &str) -> Result<ThumbSize, String> {
    match s {
        "n" => Ok(ThumbSize::Normal),
        "l" => Ok(ThumbSize::Large),
        "x" => Ok(ThumbSize::XLarge),
        "xx" => Ok(ThumbSize::XXLarge),
        _ => Err(String::from("Invalid size specification.")),
    }
}

fn main() {
    let cli = Cli::parse();
    let level = {
        if cli.debug {
            "debug"
        } else {
            "error"
        }
    };
    flexi_logger::Logger::try_with_env_or_str(level)
        .unwrap()
        .start()
        .unwrap();

    match get_thumbnail(
        cli.file,
        match cli.size {
            Some(v) => v,
            None => ThumbSize::Large,
        },
        cli.force_creation,
    ) {
        Ok(toe_path) => {
            println!("{toe_path}")
        }
        Err(e) => {
            error!("{}", e.msg());
            std::process::exit(e.error_code());
        }
    }
}
