use dbui_core::database::conn::ConnectionParams;
use dbui_core::Project;

use serde::Deserialize;

#[derive(Debug, Deserialize)]
pub struct ProjectForm {
  key: String,
  name: String,
  server: String,
  port: String,
  database: String,
  user: String,
  password: String,
  tls: bool
}

impl ProjectForm {
  pub fn key(&self) -> &String {
    &self.key
  }

  pub fn name(&self) -> &String {
    &self.name
  }

  pub fn server(&self) -> &String {
    &self.server
  }

  pub fn port(&self) -> Option<i32> {
    match &self.port {
      p if p.is_empty() => None,
      p => match p.parse() {
        Ok(i) => Some(i),
        Err(_) => None
      }
    }
  }

  pub fn database(&self) -> &String {
    &self.database
  }

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

  pub fn password(&self) -> &String {
    &self.password
  }

  pub fn tls(&self) -> bool {
    self.tls
  }

  pub fn as_project(&self) -> Project {
    let name = if self.name().is_empty() {
      self.key.clone()
    } else {
      self.name().clone()
    };
    let pass = if self.password() == "" {
      None
    } else {
      Some(self.password().clone())
    };
    let conn = ConnectionParams::new(
      self.server().clone(),
      self.port(),
      self.database().clone(),
      self.user().clone(),
      pass,
      self.tls()
    );
    Project::new(self.key().clone(), name, conn)
  }
}
