#![warn(unused_extern_crates)]
#![allow(non_snake_case)]

use diesel::{r2d2::{self, ConnectionManager}, SqliteConnection};
use dotenvy::dotenv;
use ntex_files as fs;
use ntex::web;

mod api;
mod db;
mod models;
mod providers;
mod schema;
mod status;
mod util;
mod videos;

type DbPool = r2d2::Pool<ConnectionManager<SqliteConnection>>;

static USER_AGENT: &str = "Mozilla/5.0 (iPhone; CPU iPhone OS 14_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) FxiOS/33.0 Mobile/15E148 Safari/605.1.15";
#[ntex::main]
async fn main() -> std::io::Result<()> {
    // std::env::set_var("RUST_BACKTRACE", "1");
    env_logger::init(); // You need this to actually see logs
    dotenv().ok();

    // set up database connection pool
    let connspec = std::env::var("DATABASE_URL").expect("DATABASE_URL");
    let manager = ConnectionManager::<SqliteConnection>::new(connspec);
    let pool = r2d2::Pool::builder()
        .build(manager)
        .expect("Failed to create pool.");

    let cache: util::cache::VideoCache = crate::util::cache::VideoCache::new();

    web::HttpServer::new(move || {
        web::App::new()
            .state(pool.clone())
            .state(cache.clone())
            .wrap(web::middleware::Logger::default())
            .service(web::scope("/api").configure(api::config))
            .service(
            web::resource("/")
                .route(web::get().to(|| async {
                web::HttpResponse::Found()
                    .header("Location", "hottub://source?url=hottub.spacemoehre.de")
                    .finish()
                }))
            )
            .service(fs::Files::new("/", "static").index_file("index.html"))
    })
    // .bind_openssl(("0.0.0.0", 18080), builder)?
    .bind(("0.0.0.0", 18080))?
    .run()
    .await
}
