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

use crate::forms::project_form::ProjectForm;

use dbui_service::AppConfig;

pub fn new(session: Session, cfg: web::Data<AppConfig>, req: HttpRequest) -> HttpResponse {
  crate::act(&session, &cfg, &req, |ctx| {
    let p = dbui_core::Project::new("".into(), "New".into(), dbui_core::database::conn::ConnectionParams::default());
    dbui_templates::project::project_edit::edit(&ctx, &p, true)
  })
}

pub fn create(session: Session, cfg: web::Data<AppConfig>, form: Option<web::Form<ProjectForm>>, req: HttpRequest) -> HttpResponse {
  match form {
    Some(f) => crate::redir(&session, &cfg, &req, |ctx| {
      let p = f.as_project();
      crate::util::ctx::add_flash(&session, ctx.log(), &format!("success:Project [{}] changes saved", p.key()));
      cfg.set_project(&p)?;
      ctx.router().route("home", &[&f.key()])
    }),
    None => crate::redir(&session, &cfg, &req, |ctx| {
      crate::util::ctx::add_flash(&session, ctx.log(), "error:Invalid form (details soon)");
      ctx.router().route("project.detail", &[&"ERROR"])
    })
  }
}

pub fn detail(session: Session, cfg: web::Data<AppConfig>, key: web::Path<String>, req: HttpRequest) -> HttpResponse {
  crate::act(&session, &cfg, &req, |ctx| {
    let p = ctx.app().get_project(&key)?;
    dbui_templates::project::project_detail::detail(&ctx, &p)
  })
}

pub fn edit(session: Session, cfg: web::Data<AppConfig>, key: web::Path<String>, req: HttpRequest) -> HttpResponse {
  crate::act(&session, &cfg, &req, |ctx| {
    let p = ctx.app().get_project(&key)?;
    dbui_templates::project::project_edit::edit(&ctx, &p, false)
  })
}

pub fn save(
  session: Session, cfg: web::Data<AppConfig>, key: web::Path<String>, form: Option<web::Form<ProjectForm>>, req: HttpRequest
) -> HttpResponse {
  match form {
    Some(f) => crate::redir(&session, &cfg, &req, |ctx| {
      let p = f.as_project();
      crate::util::ctx::add_flash(&session, ctx.log(), &format!("success:Project [{}] changes saved", p.key()));
      let k: &str = &key;
      if p.key() != k {
        cfg.remove_project(k)?;
      }
      cfg.set_project(&p)?;
      ctx.router().route("home", &[&p.key()])
    }),
    None => crate::redir(&session, &cfg, &req, |ctx| {
      crate::util::ctx::add_flash(&session, ctx.log(), "error:Invalid form (details soon)");
      ctx.router().route("home", &[&key])
    })
  }
}

#[derive(Debug, Deserialize)]
pub struct SqlRequest {
  sql: String
}
