//! Server lib module to host re-usable server operations.

use crate::models;
use crate::models::HoldPosition;
use crate::models::HoldRole;
use crate::server::config::Config;
use redb::Database;
use std::collections::BTreeMap;

#[tracing::instrument]
pub(crate) async fn import_mini_moonboard_problems(config: &Config, db: &Database) -> Result<(), Error> {
    use moonboard_parser::mini_moonboard;

    let mut problems = Vec::new();

    let file_name = "problems Mini MoonBoard 2020 40.json";
    let file_path = config.moonboard_problems.join(file_name);

    tracing::info!("Parsing mini moonboard problems from {file_path}");

    let set_by = "mini-mb-2020-parser";

    let mini_moonboard = mini_moonboard::parse(file_path.as_std_path()).await?;
    for problem in mini_moonboard.problems {
        let mut holds = BTreeMap::<HoldPosition, HoldRole>::new();
        for mv in problem.moves {
            let row = mv.description.row();
            let col = mv.description.column();
            let hold_position = HoldPosition { row, col };

            let role = match (mv.is_start, mv.is_end) {
                (true, true) => unreachable!(),
                (true, false) => HoldRole::Start,
                (false, true) => HoldRole::End,
                (false, false) => HoldRole::Normal,
            };
            holds.insert(hold_position, role);
        }

        // TODO:

        // let name = problem.name;

        // let method = match problem.method {
        //     mini_moonboard::Method::FeetFollowHands => models::Method::FeetFollowHands,
        //     mini_moonboard::Method::Footless => models::Method::Footless,
        //     mini_moonboard::Method::FootlessPlusKickboard => models::Method::FootlessPlusKickboard,
        // };

        // let problem = models::Problem::new(name, set_by.to_owned(), holds, method);
        // problems.push(problem);

        let problem = models::Problem { holds };
        problems.push(problem);
    }

    state
        .persistent
        .update(|s| {
            s.problems.problems.extend(problems);
        })
        .await?;

    Ok(())
}

#[derive(Debug, derive_more::Error, derive_more::Display, derive_more::From)]
pub enum Error {
    Parser(moonboard_parser::Error),
}
