use crate::files::FileService;
use dbui_core::project::ProjectSummary;
use dbui_core::{Error, Project, Result};
use dbui_database::conn::ConnectionPool;

use std::collections::HashMap;
use std::sync::Arc;

/// Manages projects, providing load/save methods for a given [FileService](crate::files::FileService) and caching connection pools.
#[derive(Debug)]
pub struct ProjectService {
  files: Arc<FileService>,
  log: slog::Logger,
  pools: HashMap<String, Arc<ConnectionPool>>
}

impl ProjectService {
  pub fn new(files: Arc<FileService>, logger: &slog::Logger) -> ProjectService {
    ProjectService {
      files,
      log: logger.new(slog::o!("service" => "project")),
      pools: HashMap::new()
    }
  }

  pub fn keys(&self) -> Result<Vec<String>> {
    Ok(self.files.list_json("projects")?)
  }

  pub fn get_all_projects(&self) -> Result<Vec<Project>> {
    self.keys()?.iter().map(|k| self.get_project(k)).collect()
  }

  pub fn get_project_summary(&self, key: &str) -> Result<ProjectSummary> {
    self.files.read_json(&format!("projects/{}", key))
  }

  pub fn get_project(&self, key: &str) -> Result<Project> {
    let summ: ProjectSummary = self.get_project_summary(key)?;
    Ok(Project::new(key.into(), summ.name, summ.connection_params))
  }

  pub fn set_project(&self, p: &Project) -> Result<()> {
    self.files.create_dir_if_needed("projects")?;
    self.files.write_json(p.to_summary(), &format!("projects/{}.json", p.key()))
  }

  pub fn remove_project(&self, key: &str) -> Result<()> {
    self.files.remove(&format!("projects/{}.json", key))
  }

  pub fn open_connection(&mut self, key: String) -> Result<postgres::Client> {
    match self.pools.get(&key) {
      Some(pool) => pool.open(),
      None => {
        let pool = ConnectionPool::new(self.get_project(&key)?.conn())?;
        let _ = self.pools.insert(key.clone(), Arc::new(pool));
        match self.pools.get(&key) {
          Some(pool) => pool.open(),
          None => Err(Error::from("Can't find newly-inserted pool"))
        }
      }
    }
  }
}
