// Copyright Claudio Mattera 2019.
// Distributed under the MIT License.
// See accompanying file License.txt, or online at
// https://opensource.org/licenses/MIT

use log::*;

use crate::webapi;

#[cfg(feature = "sqlite")]
use crate::storage::SqliteStorage;

#[cfg(feature = "postgresql")]
use crate::storage::PostgresStorage;

#[cfg(feature = "sqlite")]
pub fn sqlite_serve(
    database_path: &str,
    port: u16,
    certificate: &str,
    private_key: &str,
) -> Result<(), std::io::Error> {
    info!("Starting programm...");

    let bind_address = format!("0.0.0.0:{}", port);

    let storage: SqliteStorage =
        SqliteStorage::new(database_path).expect("Cannot initialize storage");

    webapi::main(bind_address, certificate, private_key, storage)
}

#[cfg(not(feature = "sqlite"))]
pub fn sqlite_serve(
    _database_path: &str,
    _port: u16,
    _certificate: &str,
    _private_key: &str,
) -> Result<(), std::io::Error> {
    error!("SQLite backend not available ('sqlite' feature is disabled)");
    std::process::exit(1);
}

#[cfg(feature = "postgresql")]
pub fn postgres_serve(
    database_host: &str,
    port: u16,
    certificate: &str,
    private_key: &str,
) -> Result<(), std::io::Error> {
    info!("Starting programm...");

    let bind_address = format!("0.0.0.0:{}", port);

    let storage: PostgresStorage =
        PostgresStorage::new(database_host).expect("Cannot initialize storage");

    webapi::main(bind_address, certificate, private_key, storage)
}

#[cfg(not(feature = "postgresql"))]
pub fn postgres_serve(
    _database_host: &str,
    _port: u16,
    _certificate: &str,
    _private_key: &str,
) -> Result<(), std::io::Error> {
    error!("Postgres backend not available ('postgresql' feature is disabled)");
    std::process::exit(1);
}
