pub(crate) mod sources;

mod config;
mod pixmap;

use crate::config::Config;
use actix_web::web::Data;
use actix_web::{App, HttpServer};
use std::collections::{BTreeMap, HashMap};
use std::env::args;
use std::fmt::Debug;
use std::fs;
use std::sync::Arc;
use std::time::SystemTime;
use tokio::sync::RwLock;
use wxbox_grib2::GribMessage;

pub struct AppState {
    grib2_cache: RwLock<HashMap<String, Arc<RwLock<GribMessage>>>>,
    grib2_cache_timestamps: RwLock<HashMap<String, SystemTime>>,
    config: Config,
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    tracing_subscriber::fmt::init();

    let config_path = args().nth(1).unwrap();
    let config_str = fs::read_to_string(config_path).unwrap();
    let config: Config = toml::from_str(&config_str).unwrap();

    let data = Data::new(AppState {
        grib2_cache: RwLock::new(HashMap::new()),
        grib2_cache_timestamps: RwLock::new(HashMap::new()),
        config,
    });
    HttpServer::new(move || {
        App::new()
            .service(sources::grib2::source)
            .app_data(data.clone())
    })
    .bind(("::", 8080))?
    .run()
    .await
}
