use crate::map::tiles::SourceId;
use image::DynamicImage;
use poll_promise::Promise;
use serde::{Deserialize, Serialize};
use std::fmt::{Debug, Formatter};

pub mod baselayers;
pub mod datalayers;

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct LayerSource {
    pub source_id: u64,
    pub tile_url: String,
    pub display_name: String,
    pub short_name: String,
    pub location: String,
    pub source: String,
    pub source_link: String,
    pub type_hint: LayerTypeHint,
    pub tile_size: u32,
    pub max_zoom: u8,
}

#[derive(Serialize, Deserialize, Copy, Clone, Debug)]
pub enum LayerTypeHint {
    Baselayer,
    RadarData,
}
impl LayerTypeHint {
    pub fn icon(&self) -> &'static str {
        match self {
            LayerTypeHint::Baselayer => egui_phosphor::regular::MAP_TRIFOLD,
            LayerTypeHint::RadarData => egui_phosphor::regular::TARGET,
        }
    }
    pub fn name(&self) -> &'static str {
        match self {
            LayerTypeHint::Baselayer => "Baselayer",
            LayerTypeHint::RadarData => "Radar data",
        }
    }
}

pub struct Tile {
    pub promise: Promise<Result<DynamicImage, String>>,
}
impl Debug for Tile {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            if self.promise.ready().is_some() {
                "<loaded texture>"
            } else {
                "<texture promise>"
            }
        )
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub struct ActiveLayer {
    pub source_id: SourceId,
    pub layer_id: LayerId,
    pub visible: bool,
}

#[derive(Hash, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct LayerId(u32);
impl LayerId {
    pub fn new() -> Self {
        Self(rand::random())
    }
}
impl Debug for LayerId {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:04x}", self.0)
    }
}
impl From<LayerId> for egui::Id {
    fn from(id: LayerId) -> Self {
        Self::new(id)
    }
}
