use rocket_contrib::serve::StaticFiles;
use rocket_contrib::json::Json;
use rocket::response::content;
// use rocket::http::ContentType;
// use rocket::response::Response;
use std::sync::Mutex;
use std::collections::HashMap;
use super::ACCOUNTS;
use super::query::*;
use reqwest;
use urldecode;

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

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


pub fn proxy(url: &str) -> Vec<u8> {
    match reqwest::blocking::get(url) {
        Ok(mut resp) => {
            // println!("resp = {:?}", resp);
            let mut buf: Vec<u8> = vec![];
            match resp.copy_to(&mut buf) {
                Ok(_r) => buf,
                Err(_e) => vec![]
            }

        }
        Err(_e) => vec![]
    }

}


#[get("/proxy/<url>")]
fn proxy_gate(url: String)  -> Vec<u8>{
    // let html = ContentType::parse_flexible("image/jpeg").unwrap();
    // let response = Response::build().header(html).finalize();
    proxy(&urldecode::decode(url))
}


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

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

    let accountmap = json_account.into_inner();
    let accountnames: Vec<String> = accountmap.keys().map(|x| x.into()).collect();
    if let Some(accountname) = accountnames.get(0) {
        if let Some(account) = accountmap.get(accountname) {
            let client = reqwest::blocking::Client::builder().build().unwrap();
            let updated_acc = account.updated(&client);
            let mut accounts = ACCOUNTS.lock().unwrap();
            accounts.insert(accountname.into(), updated_acc);
            drop(accounts);
            return "Inserted"
        }
    }
    // dbg!(&accounts);
    // run_update();
    "Not updated"
}

#[get("/load/<account>")]
fn load(account: String) -> content::Json<String> {
    // println!("U want: {}",account);
    // let guard = ACCOUNTS.clone();
    let guard = ACCOUNTS.lock().unwrap().clone();
    // println!("LCK get");
    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())
    }
}

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