mod app_state;
mod static_files;
mod tls_config;
mod website;
use actix_web::{get, App, HttpResponse, HttpServer, Responder};
use app_state::AppState;
use static_files::StaticFilesManager;
use std::path::PathBuf;
use tls_config::tls_config;
use website::WebSite;

#[get("/{pth:.*}")]
async fn page(
    website: actix_web::web::Data<WebSite>,
    pth: actix_web::web::Path<PathBuf>,
) -> impl Responder {
    let pth = pth.into_inner();
    match website.get_page_by_url(&pth) {
        Some(page) => HttpResponse::Ok().body(page.html_doc.to_string()),
        None => HttpResponse::NotFound().body(format!("Not found {}", pth.display())),
    }
}

#[get("/admin/dashboard")]
async fn admin_dashboard() -> impl Responder {
    HttpResponse::Ok().body("Admin")
}

#[get("/admin/login")]
async fn admin_login() -> impl Responder {
    HttpResponse::Ok().body("Login")
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let app_state = AppState::new();
    let website = WebSite::load(&app_state.config);
    let mut static_files_manager = StaticFilesManager::new(&app_state).unwrap();
    static_files_manager.build_index().unwrap();

    let host = app_state.config.host.clone();
    let port = app_state.config.port;
    let port_tls = app_state.config.port_tls;

    let srv_conf = tls_config(&app_state.config);

    let static_files_manager =
        actix_web::web::Data::new(std::sync::Mutex::new(static_files_manager));

    let app_state = actix_web::web::Data::new(std::sync::Mutex::new(app_state));

    HttpServer::new(move || {
        App::new()
            .wrap(actix_web::middleware::Logger::default())
            .wrap(actix_web::middleware::Compress::default())
            .app_data(actix_web::web::Data::clone(&app_state))
            .app_data(actix_web::web::Data::clone(&static_files_manager))
            .app_data(actix_web::web::Data::new(website.clone()))
            .service(admin_dashboard)
            .service(admin_login)
            .service(page)
    })
    .bind(format!("{}:{}", host, port))?
    .bind_rustls(format!("{}:{}", host, port_tls), srv_conf)?
    .run()
    .await
}