use std::collections::HashMap;
use std::convert::{From, Into, TryFrom, TryInto};

use rand::Rng;
use crate::ship::map::Maps;
use crate::ship::drops::DropTable;
use crate::entity::character::SectionID;
use crate::ship::monster::{load_monster_stats_table, MonsterType, MonsterStats};
use crate::ship::map::area::MapAreaLookup;

#[derive(Debug)]
pub enum RoomCreationError {
    InvalidMode,
    InvalidEpisode(u8),
    InvalidDifficulty(u8),

}

#[derive(Debug, Copy, Clone, derive_more::Display)]
pub enum Episode {
    #[display(fmt="ep1")]
    One,
    #[display(fmt="ep2")]
    Two,
    #[display(fmt="ep4")]
    Four,
}

impl TryFrom<u8> for Episode {
    type Error = RoomCreationError;

    fn try_from(value: u8) -> Result<Episode, RoomCreationError> {
        match value {
            1 => Ok(Episode::One),
            2 => Ok(Episode::Two),
            3 => Ok(Episode::Four),
            _ => Err(RoomCreationError::InvalidEpisode(value))
        }
    }
}

impl Into<u8> for Episode {
    fn into(self) -> u8 {
        match self {
            Episode::One => 1,
            Episode::Two => 2,
            Episode::Four => 3,
        }
    }
}

impl Episode {
    pub fn from_quest(value: u8) -> Result<Episode, RoomCreationError> {
        match value {
            0 => Ok(Episode::One),
            1 => Ok(Episode::Two),
            2 => Ok(Episode::Four),
            _ => Err(RoomCreationError::InvalidEpisode(value))
        }
    }
}

#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, derive_more::Display)]
pub enum Difficulty {
    Normal,
    Hard,
    VeryHard,
    Ultimate,
}

impl TryFrom<u8> for Difficulty {
    type Error = RoomCreationError;

    fn try_from(value: u8) -> Result<Difficulty, RoomCreationError> {
        match value {
            0 => Ok(Difficulty::Normal),
            1 => Ok(Difficulty::Hard),
            2 => Ok(Difficulty::VeryHard),
            3 => Ok(Difficulty::Ultimate),
            _ => Err(RoomCreationError::InvalidDifficulty(value))
        }
    }
}

impl Into<u8> for Difficulty {
    fn into(self) -> u8 {
        match self {
            Difficulty::Normal => 0,
            Difficulty::Hard => 1,
            Difficulty::VeryHard => 2,
            Difficulty::Ultimate => 3,
        }
    }
}

#[derive(Debug, Copy, Clone)]
pub enum RoomMode {
    Single {
        episode: Episode,
        difficulty: Difficulty,
    },
    Multi {
        episode: Episode,
        difficulty: Difficulty,
    },
    Challenge {
        episode: Episode,
    },
    Battle {
        episode: Episode,
        difficulty: Difficulty,
    }
}


impl RoomMode {
    pub fn difficulty(&self) -> Difficulty {
        match self {
            RoomMode::Single {difficulty, ..} => *difficulty,
            RoomMode::Multi {difficulty, ..} => *difficulty,
            RoomMode::Battle {difficulty, ..} => *difficulty,
            RoomMode::Challenge {..} => Difficulty::Normal,
        }
    }

    pub fn episode(&self) -> Episode {
        match self {
            RoomMode::Single {episode, ..} => *episode,
            RoomMode::Multi {episode, ..} => *episode,
            RoomMode::Battle {episode, ..} => *episode,
            RoomMode::Challenge {episode, ..} => *episode,
        }
    }

    pub fn battle(&self) -> u8 {
        match self {
            RoomMode::Battle {..} => 1,
            _ => 0,
        }
    }

    pub fn challenge(&self) -> u8 {
        match self {
            RoomMode::Challenge {..} => 1,
            _ => 0,
        }
    }

    pub fn single_player(&self) -> u8 {
        match self {
            RoomMode::Single {..} => 1,
            _ => 0,
        }
    }
}


pub struct RoomState {
    pub mode: RoomMode,
    pub name: String,
    pub password: [u16; 16],
    pub maps: Maps,
    pub drop_table: Box<DropTable<rand_chacha::ChaCha20Rng>>,
    pub section_id: SectionID,
    pub random_seed: u32,
    pub bursting: bool,
    pub monster_stats: Box<HashMap<MonsterType, MonsterStats>>,
    pub map_areas: MapAreaLookup,
    // items on ground
    // enemy info
}

impl RoomState {
    pub fn get_flags_for_room_list(&self) -> u8 {
        let mut flags = 0u8;
        
        match self.mode {
            RoomMode::Single {..} => {flags += 0x04}
            RoomMode::Battle {..} => {flags += 0x10},
            RoomMode::Challenge {..} => {flags += 0x20},
            _ => {flags += 0x40},
        };
        
        if self.password[0] > 0 {
            flags += 0x02;
        }
        flags
    }

    pub fn get_episode_for_room_list(&self) -> u8 {
        let episode: u8 = self.mode.episode().into();

        match self.mode {
            RoomMode::Single {..} => episode + 0x10,
            _ => episode + 0x40,
        }
    }

    pub fn get_difficulty_for_room_list(&self) -> u8 {
        let difficulty: u8 = self.mode.difficulty().into();
        difficulty + 0x22
    }

    pub fn from_create_room(create_room: &libpso::packet::ship::CreateRoom, section_id: SectionID) -> Result<RoomState, RoomCreationError> {
        if [create_room.battle, create_room.challenge, create_room.single_player].iter().sum::<u8>() > 1 {
            return Err(RoomCreationError::InvalidMode)
        }
        
        let room_mode = if create_room.battle == 1 {
            RoomMode::Battle {
                episode: create_room.episode.try_into()?,
                difficulty: create_room.difficulty.try_into()?,
            }
        }
        else if create_room.challenge == 1 {
            RoomMode::Challenge {
                episode: create_room.episode.try_into()?,
            }
        }
        else if create_room.single_player == 1 {
            RoomMode::Single {
                episode: create_room.episode.try_into()?,
                difficulty: create_room.difficulty.try_into()?,
            }
        }
        else { // normal multimode
            RoomMode::Multi {
                episode: create_room.episode.try_into()?,
                difficulty: create_room.difficulty.try_into()?,
            }
        };

        Ok(RoomState {
            monster_stats: Box::new(load_monster_stats_table(&room_mode)),
            mode: room_mode,
            random_seed: rand::thread_rng().gen(),
            name: String::from_utf16_lossy(&create_room.name).trim_matches(char::from(0)).into(),
            password: create_room.password,
            maps: Maps::new(room_mode),
            section_id: section_id,
            drop_table: Box::new(DropTable::new(room_mode.episode(), room_mode.difficulty(), section_id)),
            bursting: false,
            map_areas: MapAreaLookup::new(&room_mode.episode()),
        })
    }
}