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

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

const FLASH_KEY: &str = "flash";

pub fn req_context(session: &Session, cfg: &web::Data<AppConfig>, req: &HttpRequest, action_key: &'static str) -> RequestContext {
  let app_cfg = cfg.get_ref().clone();
  let user_profile: UserProfile = dbui_service::profile::load(app_cfg.files(), app_cfg.root_logger());
  let router = crate::util::router::RequestRouter::new(req.clone());
  let logger = app_cfg
    .root_logger()
    .new(slog::o!("action" => action_key, "user_id" => user_profile.name().clone()));
  let flash: Option<(String, String)> = match session.get(FLASH_KEY) {
    Ok(f) => f.map(|t: String| match t.find(':') {
      Some(idx) => (t[..idx].into(), t[(idx + 1)..].into()),
      None => ("".into(), t.clone())
    }),
    Err(e) => {
      slog::warn!(logger, "Unable to read from session: {}", e);
      None
    }
  };
  match flash.clone().map(|_| session.remove(FLASH_KEY)) {
    Some(_) => (),
    None => slog::warn!(logger, "Unable to remove from session")
  };

  RequestContext::new(app_cfg, user_profile, router, logger, flash)
}

pub fn add_flash(s: &Session, logger: &slog::Logger, msg: &str) {
  match s.set(FLASH_KEY, msg) {
    Ok(_) => (),
    Err(e) => slog::warn!(logger, "Unable to write to session: {}", e)
  };
}
