use rocket_contrib::serve::StaticFiles;
use rocket_contrib::json::Json;
use rocket::response::content;
use std::sync::Mutex;
use std::collections::HashMap;
use super::ACCOUNTS;
use super::query::*;

#[derive(Serialize, Deserialize, Debug, Clone)]
struct Task {
    description: String,
    complete: bool
}

lazy_static! {
    static ref TASKS: Mutex<Vec<Task>> = Mutex::new(vec![]);
}

#[get("/")]
fn index() -> &'static str {
    let accounts = ACCOUNTS.lock().unwrap();
    dbg!(&*accounts);
    drop(accounts);
    "Base url"
}

#[post("/save", data = "<account>")] //<tasks> means that the function below will have a var called tasks
fn save(account: Json<HashMap<String, Account>>) -> &'static str {
    dbg!(&account);

    let mut accounts = ACCOUNTS.lock().unwrap();
    accounts.extend(account.into_inner());
    dbg!(&accounts);
    drop(accounts);
    "Inserted"
}

// turn tasks into json (serialize)
#[get("/load/<account>")]
fn load(account: String) -> content::Json<String> {
    // get a lock here on TASKS
    let guard = ACCOUNTS.lock().unwrap().clone();
    // drop(ACCOUNTS);
    // serialize all tasks
    match guard.get(&account) {
        Some(accountdata) => {
            let json_string = serde_json::to_string(&accountdata.queries).unwrap();
            content::Json(json_string)
        },
        None => content::Json("{}".to_string())
    }
    
    // hand them out to the browser (or anything else) and tell them to expect json
}

pub fn run() {
    rocket::ignite()
    // .mount("/", routes![index])
    .mount("/", routes![save])
    .mount("/", routes![load])
    .mount("/", StaticFiles::from("webapp"))
    .launch();
}