use actix_session::Session;
use actix_web::{web, HttpRequest, HttpResponse};

use crate::forms::profile_form::ProfileForm;

use dbui_core::profile::UserProfile;
use dbui_core::Error;
use dbui_service::AppConfig;

pub fn index(session: Session, cfg: web::Data<AppConfig>, req: HttpRequest) -> HttpResponse {
  crate::act(&session, &cfg, &req, |ctx| {
    let p = ctx.app().get_all_projects()?;
    dbui_templates::home::index(&ctx, p)
  })
}

pub fn health() -> HttpResponse {
  HttpResponse::Ok().finish()
}

pub fn profile(session: Session, cfg: web::Data<AppConfig>, req: HttpRequest) -> HttpResponse {
  crate::act(&session, &cfg, &req, |ctx| dbui_templates::profile::profile(&ctx))
}

pub fn profile_post(session: Session, cfg: web::Data<AppConfig>, req: HttpRequest, form: Option<web::Form<ProfileForm>>) -> HttpResponse {
  match form {
    Some(f) => crate::redir(&session, &cfg, &req, |ctx| {
      let profile = UserProfile::new(
        String::from(f.username()),
        f.theme(),
        f.navbar_color().into(),
        f.link_color().into()
      );
      cfg.files().write_json(profile, "profile")?;
      ctx.router().route_simple("profile")
    }),
    None => crate::redir(&session, &cfg, &req, |ctx| ctx.router().route_simple("profile"))
  }
}

pub fn settings(session: Session, cfg: web::Data<AppConfig>, req: HttpRequest) -> HttpResponse {
  crate::act(&session, &cfg, &req, |ctx| dbui_templates::settings::settings(&ctx))
}

pub fn settings_post(session: Session, cfg: web::Data<AppConfig>, req: HttpRequest) -> HttpResponse {
  crate::act(&session, &cfg, &req, |ctx| dbui_templates::settings::settings(&ctx))
}

pub fn testbed_key(session: Session, cfg: web::Data<AppConfig>, key: web::Path<String>, req: HttpRequest) -> HttpResponse {
  crate::act(&session, &cfg, &req, |ctx| {
    let k: &str = &key;
    match k {
      "dump" => dbui_templates::testbed::dump(&ctx),
      "gallery" => dbui_templates::testbed::gallery(&ctx),
      "prototype" => dbui_templates::testbed::prototype(&ctx),
      "scroll" => dbui_templates::testbed::scroll(&ctx),
      _ => Err(Error::from(format!("Cannot find testbed matching [{}]", key)))
    }
  })
}
