use hashbrown::HashMap;
use rusqlite::Connection;
use serde_json::Value;

#[derive(Clone)]
pub struct ImportData(pub(crate) Vec<ImportGroup>);

#[derive(Clone, Debug)]
pub struct ImportGroup {
    pub id: u64,
    pub name: String,
    pub fields: Vec<String>,
    pub length: u64,
    pub mapping: HashMap<String, String>,
    pub imported: bool,
}

#[derive(Clone)]
pub struct ImportNote {
    pub tags: String,
    pub fields: Vec<String>,
}

pub fn load_groups(connection: &Connection) -> ImportData {
    let json_models: String = connection
        .query_one("select models from col", (), |row| row.get(0))
        .unwrap();
    let raw: Value = serde_json::from_str(json_models.as_str()).unwrap();
    let sets = raw.as_object().unwrap();
    let mut total_data = ImportData(vec![]);

    let mut count_stmt = connection
        .prepare("select mid, count(id) from notes group by mid")
        .unwrap();

    let counts = count_stmt
        .query_map([], |row| Ok((row.get(0)?, row.get(1)?)))
        .unwrap()
        .map(|x| x.unwrap())
        .collect::<Vec<(i64, i64)>>();

    for (_, collection) in sets {
        let fields = collection["flds"]
            .as_array()
            .unwrap()
            .iter()
            .map(|x| x["name"].as_str().unwrap().to_string())
            .collect();
        let mut group = ImportGroup {
            id: collection["id"].as_u64().unwrap(),
            name: collection["name"].as_str().unwrap().to_string(),
            fields,
            mapping: Default::default(),
            length: 0,
            imported: false,
        };
        if let Some((_, count)) = counts.iter().find(|(id, _)| *id == group.id as i64) {
            group.length = *count as u64
        }
        println!("{:?}", group);
        total_data.0.push(group);
    }
    total_data
}

pub fn get_words_of_group(connection: &Connection, group_id: u64) -> Vec<ImportNote> {
    let mut count_stmt = connection
        .prepare("select tags, flds from notes where mid == ?1;")
        .unwrap();

    count_stmt
        .query_map((group_id as i64,), |row| {
            Ok(ImportNote {
                tags: row.get(0)?,
                fields: row
                    .get::<usize, String>(1)?
                    .split('')
                    .map(|x| x.to_string())
                    .collect(),
            })
        })
        .unwrap()
        .map(|x| x.unwrap())
        .collect::<Vec<ImportNote>>()
}
