use slog;

use crate::cfg::AppConfig;
use dbui_core::profile::UserProfile;
use dbui_core::Result;

/// Provides reverse routing of urls
pub trait Router {
  fn route(&self, path: &str, args: &[&str]) -> Result<String>;
  fn route_simple(&self, path: &str) -> Result<String> {
    const NO_PARAMS: [&str; 0] = [];
    self.route(path, &NO_PARAMS)
  }
  fn route_static(&self, path: &str, filename: &str, ext: &str) -> Result<String> {
    let p = format!("{}/{}.{}", path, filename, ext);
    self.route("static", &[&p])
  }
}

/// Contains information about the application and current user, along with common components
pub struct RequestContext {
  app: AppConfig,
  user: UserProfile,
  router: Box<dyn Router + 'static>,
  flash: Option<(String, String)>,
  log: slog::Logger
}

impl std::fmt::Debug for RequestContext {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    write!(f, "RequestContext [{:?}] [{:?}]", self.user, self.app)
  }
}

impl RequestContext {
  pub fn new(
    app: AppConfig, user: UserProfile, router: impl Router + 'static, log: slog::Logger, flash: Option<(String, String)>
  ) -> RequestContext {
    RequestContext {
      app,
      user,
      router: Box::new(router),
      flash,
      log
    }
  }

  pub fn app(&self) -> &AppConfig {
    &self.app
  }

  pub fn user(&self) -> &UserProfile {
    &self.user
  }

  #[allow(clippy::borrowed_box)]
  pub fn router(&self) -> &Box<dyn Router + 'static> {
    &self.router
  }

  pub fn flash(&self) -> &Option<(String, String)> {
    &self.flash
  }

  pub fn log(&self) -> &slog::Logger {
    &self.log
  }
}
