mod args;
mod log;
mod server;

#[cfg(test)]
pub mod tests;

use dbui_service::AppConfig;

#[cfg(debug_assertions)]
fn is_debug() -> bool {
  true
}

#[cfg(not(debug_assertions))]
fn is_debug() -> bool {
  false
}

pub fn go() -> std::io::Result<()> {
  let matches = args::get_matches();
  let verbose = matches.is_present("verbose") || is_debug();
  let log = crate::log::root_logger(verbose);
  let cfg_dir = match matches.value_of("config") {
    None => default_cfg_dir(&log),
    Some(o) => o.into()
  };
  let address = match matches.value_of("address") {
    None => "127.0.0.1",
    Some(o) => o
  };
  let port: i32 = match matches.value_of("port") {
    Some(p) => match p.parse() {
      Ok(p) => p,
      Err(_) => {
        slog::warn!(log, "Can't parse port number from [{}]", p);
        4200
      }
    },
    None => 4200
  };
  let cfg = AppConfig::new(cfg_dir, address.into(), port, verbose, log);
  server::start_server(cfg)
}

fn default_cfg_dir(log: &slog::Logger) -> String {
  let app_info = app_dirs2::AppInfo {
    name: dbui_core::APPNAME,
    author: "kyleu"
  };
  let ret: String = match app_dirs2::get_app_root(app_dirs2::AppDataType::UserConfig, &app_info) {
    Ok(d) => d.to_string_lossy().into(),
    Err(e) => {
      slog::warn!(log, "Cannot find default config directory: [{:?}]", e);
      ".".into()
    }
  };
  ret
}

#[no_mangle]
pub extern "C" fn libgo() {
  match go() {
    Ok(_) => println!("Successfully started [{}]", dbui_core::APPNAME),
    Err(e) => println!("Error starting [{}]: {:?}", dbui_core::APPNAME, e)
  };
}

#[cfg(target_os = "android")]
#[allow(non_snake_case)]
pub mod android {
  extern crate jni;

  use self::jni::objects::JClass;
  use self::jni::JNIEnv;
  use super::go;

  #[no_mangle]
  pub unsafe extern "C" fn Java_com_kyleu_dbui_Dbui_go(env: JNIEnv, _: JClass) {
    println!("Android!");
    go();
  }
}
