use rusqlite::Connection;

use std::{fs, io::ErrorKind, path::PathBuf, sync::RwLock};

pub static PROGRAM_HOME_PATH: RwLock<std::string::String> = RwLock::new(String::new());
pub static DB_PATH: RwLock<std::string::String> = RwLock::new(String::new());
pub static IMAGES_STORE_PATH: RwLock<std::string::String> = RwLock::new(String::new());

pub fn init() {
    let program_home_path = if cfg!(target_os = "windows") {
        let binding = std::env::var("APP_DATA").expect("No APP_DATA directory");
        let appdata = PathBuf::from(&binding);

        appdata.join("learn-hieroglyph")
    } else {
        let binding = std::env::var("HOME").expect("No HOME directory");
        let home = PathBuf::from(&binding);

        home.join(".config/learn-hieroglyph")
    };

    match fs::create_dir_all(&program_home_path) {
        Ok(_) => {},
        Err(error) => match error.kind() {
            ErrorKind::AlreadyExists => {},
            _ => panic!("Could not create app home folder: {}", &program_home_path.to_str().unwrap())
        }
    };

    let mut binding = PROGRAM_HOME_PATH.write().unwrap();
    *binding = program_home_path.as_path().to_str().unwrap().to_string();

    let db_path = program_home_path.join("db.sqlite");
    let mut binding = DB_PATH.write().unwrap();
    *binding = db_path.as_path().to_str().unwrap().to_string();

    let images_store_path = program_home_path.join("images/");
    let mut binding = IMAGES_STORE_PATH.write().unwrap();
    *binding = images_store_path.as_path().to_str().unwrap().to_string();

    let connection = Connection::open(db_path).unwrap();

    connection.execute("CREATE TABLE IF NOT EXISTS cards (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        imagename CHAR(64),
        hieroglyph VARCHAR(64),
        reading VARCHAR(64),
        translation VARCHAR(128),
        is_learning BOOLEAN DEFAULT FALSE
    )",()).unwrap();
}


pub fn get_program_home_path() -> String {
    (*PROGRAM_HOME_PATH.read().unwrap()).clone()
}

pub fn get_db_path() -> String {
    (*DB_PATH.read().unwrap()).clone()
}

pub fn get_images_store_path() -> String {
    (*IMAGES_STORE_PATH.read().unwrap()).clone()
}
