use rocket::http::{ContentType, Status};
use rocket::request::Request;
use rocket::response::{self, Responder, Response};
use rocket::serde::json::Json;
use rocket_i18n::{I18n, Translations};
use serde_json::json;
use std::io::Cursor;

use crate::web::vks::response::*;
use rocket::serde::json::Error as JsonError;

pub mod json {
    use crate::web::vks::response::EmailStatus;
    use serde_derive::{Deserialize, Serialize};
    use std::collections::HashMap;

    #[derive(Deserialize)]
    pub struct VerifyRequest {
        pub token: String,
        pub addresses: Vec<String>,
        pub locale: Option<Vec<String>>,
    }

    #[derive(Deserialize)]
    pub struct UploadRequest {
        pub keytext: String,
    }

    #[derive(Serialize, Deserialize)]
    pub struct UploadResult {
        pub token: String,
        pub key_fpr: String,
        pub status: HashMap<String, EmailStatus>,
    }
}

pub type JsonResult = Result<serde_json::Value, JsonErrorResponse>;

#[derive(Debug)]
pub struct JsonErrorResponse(pub Status, pub String);

impl<'r> Responder<'r, 'static> for JsonErrorResponse {
    fn respond_to(self, _: &'r Request<'_>) -> response::Result<'static> {
        let error_json = json!({"error": self.1});
        Response::build()
            .status(self.0)
            .sized_body(None, Cursor::new(error_json.to_string()))
            .header(ContentType::JSON)
            .ok()
    }
}

pub fn json_or_error<T>(data: Result<Json<T>, JsonError>) -> Result<Json<T>, JsonErrorResponse> {
    match data {
        Ok(data) => Ok(data),
        Err(JsonError::Io(_)) => Err(JsonErrorResponse(
            Status::InternalServerError,
            "i/o error!".to_owned(),
        )),
        Err(JsonError::Parse(_, e)) => Err(JsonErrorResponse(Status::BadRequest, e.to_string())),
    }
}

pub fn upload_ok_json(response: UploadResponse) -> Result<serde_json::Value, JsonErrorResponse> {
    match response {
        UploadResponse::Ok {
            token,
            key_fpr,
            status,
            ..
        } => Ok(json!(json::UploadResult {
            token,
            key_fpr,
            status
        })),
        UploadResponse::OkMulti { key_fprs } => Ok(json!(key_fprs)),
        UploadResponse::Error(error) => Err(JsonErrorResponse(Status::BadRequest, error)),
    }
}

pub fn get_locale(langs: &rocket::State<Translations>, locales: Vec<String>) -> I18n {
    locales
        .iter()
        .flat_map(|lang| lang.split(['-', ';', '_']).next())
        .flat_map(|lang| langs.iter().find(|(trans, _)| trans == &lang))
        .next()
        .or_else(|| langs.iter().find(|(trans, _)| trans == &"en"))
        .map(|(lang, catalog)| I18n {
            catalog: catalog.clone(),
            lang,
        })
        .expect("Expected to have an english translation!")
}
