use std::collections::BTreeMap;
use std::f64::consts::PI;
use std::io::{BufWriter, Cursor, Read};
use std::time::{SystemTime};
use actix_web::{get, HttpResponse, web};
use actix_web::http::{header, StatusCode};
use actix_web::web::Data;
use eccodes::{CodesHandle, FallibleStreamingIterator, ProductKind};
use flate2::read::GzDecoder;
use ndarray::{Zip};
use ordered_float::{FloatCore, OrderedFloat};
use png::{BitDepth, ColorType, Encoder};
use wxbox_pal::{Color, ColorPalette, create_test_palette};
use crate::{AppState, LutKey};
use crate::grib2::{closest_key, LookupTable2D};
use crate::pixmap::Pixmap;
use crate::sources::grib2::{eccodes_remap, load, needs_reload, reload_if_required, render};

#[get("/noaa_mrms_merged_composite_reflectivity_qc/{z}/{x}/{y}.png")]
async fn mrms_cref(path: web::Path<(i32, u32, u32)>, data: Data<AppState>) -> HttpResponse {
    let pal = create_test_palette();

    reload_if_required(
        "https://mrms.ncep.noaa.gov/data/2D/MergedReflectivityQCComposite/MRMS_MergedReflectivityQCComposite.latest.grib2.gz",
        true,
        120,
        LutKey::NoaaMrmsMergedCompositeReflectivityQc,
        &data.lut_cache_timestamps,
        &data.lut_cache
    ).await;

    if let Some(map) = data.lut_cache.read().await.get(&LutKey::NoaaMrmsMergedCompositeReflectivityQc) {
        HttpResponse::Ok()
            .insert_header(header::ContentType(mime::IMAGE_PNG))
            .body(render(path.1 as f64, path.2 as f64, path.0, 256, pal, map))
    } else {
        HttpResponse::new(StatusCode::NOT_FOUND)
    }
}

