use uuid::Uuid;
use rand::prelude::*;
use serde_cbor::{from_slice, to_vec};

use postgres::transaction::Transaction;

use failure::Error;
use failure::err_msg;

use account::{Account};
use rpc::{CrypSpawnParams};
use skill::{Skill, Cooldown, Effect, Cast, Category, Immunity, Disable, Event};
use spec::{Spec};
use vbox::Var;

#[derive(Debug,Clone,Serialize,Deserialize)]
pub struct Colours {
    pub red: u8,
    pub green: u8,
    pub blue: u8,
}

impl Colours {
    pub fn new() -> Colours {
        Colours { red: 0, green: 0, blue: 0 }
    }

    pub fn from_cryp(cryp: &Cryp) -> Colours {
        let mut count = Colours::new();

        for spec in cryp.specs.iter() {
            let v = Var::from(*spec);
            v.colours(&mut count);
        }

        for cs in cryp.skills.iter() {
            let v = Var::from(cs.skill);
            v.colours(&mut count);
        }

        count
    }
}


#[derive(Debug,Clone,Copy,PartialEq,Serialize,Deserialize)]
pub struct CrypSkill {
    pub skill: Skill,
    pub self_targeting: bool,
    pub cd: Cooldown,
}

impl CrypSkill {
    pub fn new(skill: Skill) -> CrypSkill {
        CrypSkill {
            skill,
            self_targeting: skill.self_targeting(),
            cd: skill.base_cd(),
        }
    }
}

#[derive(Debug,Clone,Copy,PartialEq,Serialize,Deserialize)]
pub enum EffectMeta {
    TickAmount(u64),
    AddedDamage(u64),
}

#[derive(Debug,Clone,PartialEq,Serialize,Deserialize)]
pub struct CrypEffect {
    pub effect: Effect,
    pub duration: u8,
    pub meta: Option<EffectMeta>,
    pub tick: Option<Cast>,
}

impl CrypEffect {
    pub fn new(effect: Effect) -> CrypEffect {
        CrypEffect { effect, duration: effect.duration(), meta: None, tick: None }
    }

    pub fn set_tick(mut self, tick: Cast) -> CrypEffect {
        self.tick = Some(tick);
        self
    }

    pub fn set_meta(mut self, meta: EffectMeta) -> CrypEffect {
        self.meta = Some(meta);
        self
    }
}

#[derive(Debug,Clone,Copy,PartialEq,Serialize,Deserialize)]
pub enum Stat {
    Str,
    Agi,
    Int,
    Hp,
    Speed,
    RedDamage,
    RedDamageTaken,
    BlueDamage,
    BlueDamageTaken,
    GreenDamage,
    GreenDamageTaken,
    RedShield,
    BlueShield,
    Evasion,
}

#[derive(Debug,Clone,Copy,PartialEq,Serialize,Deserialize)]
pub struct CrypStat {
    base: u64,
    value: u64,
    max: u64,
    pub stat: Stat,
}

impl CrypStat {
    // pub fn set(&mut self, v: u64, specs: &Vec<Spec>) -> &mut CrypStat {
    //     self.base = v;
    //     self.recalculate(specs)
    // }

    pub fn recalculate(&mut self, specs: &Vec<Spec>, team_colours: &Colours) -> &mut CrypStat {
        let specs = specs
            .iter()
            .filter(|s| s.affects().contains(&self.stat))
            .map(|s| *s)
            .collect::<Vec<Spec>>();

        // applied with fold because it can be zeroed or multiplied
        // but still needs access to the base amount
        let value = specs.iter().fold(self.base, |acc, s| s.apply(acc, self.base, team_colours));
        self.value = value;
        self.max = value;

        self
    }

    pub fn reduce(&mut self, amt: u64) -> &mut CrypStat {
        self.value = self.value.saturating_sub(amt);
        self
    }

    pub fn increase(&mut self, amt: u64) -> &mut CrypStat {
        self.value = *[
            self.value.saturating_add(amt),
            self.max
        ].iter().min().unwrap();

        self
    }

    pub fn force(&mut self, v: u64) -> &mut CrypStat {
        self.base = v;
        self.value = v;
        self.max = v;

        self
    }
}

#[derive(Debug,Clone,Serialize,Deserialize)]
pub struct CrypRecover {
    pub id: Uuid,
    pub account: Uuid,
    pub name: String,
}

#[derive(Debug,Clone,Serialize,Deserialize)]
pub struct Cryp {
    pub id: Uuid,
    pub account: Uuid,
    pub red_damage: CrypStat,
    pub red_shield: CrypStat,
    pub blue_shield: CrypStat,
    pub blue_damage: CrypStat,
    pub green_damage: CrypStat,
    pub speed: CrypStat,
    pub hp: CrypStat,
    pub evasion: CrypStat,
    pub skills: Vec<CrypSkill>,
    pub effects: Vec<CrypEffect>,
    pub specs: Vec<Spec>,
    pub colours: Colours,
    pub name: String,
}

impl Cryp {
    pub fn new() -> Cryp {
        let id = Uuid::new_v4();
        return Cryp {
            id,
            account: id,
            red_damage: CrypStat { base: 256, value: 256, max: 256, stat: Stat::RedDamage },
            red_shield: CrypStat { base: 0, value: 0, max: 0, stat: Stat::RedShield },
            blue_damage: CrypStat { base: 256, value: 256, max: 256, stat: Stat::BlueDamage },
            blue_shield: CrypStat { base: 0, value: 0, max: 0, stat: Stat::BlueShield },
            green_damage: CrypStat { base: 256, value: 256, max: 256, stat: Stat::GreenDamage },
            hp: CrypStat { base: 1024, value: 1024, max: 1024, stat: Stat::Hp },
            speed: CrypStat { base: 128, value: 128, max: 128, stat: Stat::Speed },
            evasion: CrypStat { base: 0, value: 0, max: 0, stat: Stat::Evasion },
            skills: vec![],
            effects: vec![],
            specs: vec![],
            colours: Colours::new(),
            name: String::new(),
        };
    }

    pub fn named(mut self, name: &String) -> Cryp {
        self.name = name.clone();
        self
    }

    pub fn set_account(mut self, account: Uuid) -> Cryp {
        self.account = account;
        self
    }

    pub fn learn(mut self, s: Skill) -> Cryp {
        self.skills.push(CrypSkill::new(s));
        self.colours = Colours::from_cryp(&self);
        self
    }

    pub fn learn_mut(&mut self, s: Skill) -> &mut Cryp {
        self.skills.push(CrypSkill::new(s));
        self.calculate_colours()
    }

    pub fn forget(&mut self, skill: Skill) -> Result<&mut Cryp, Error> {
        match self.skills.iter().position(|s| s.skill == skill) {
            Some(i) => {
                self.skills.remove(i);
                return Ok(self.calculate_colours());
            },
            None => Err(format_err!("{:?} does not know {:?}", self.name, skill)),
        }
    }

    pub fn spec_add(&mut self, spec: Spec) -> Result<&mut Cryp, Error> {
        self.specs.push(spec);
        return Ok(self.calculate_colours());
    }

    pub fn spec_remove(&mut self, spec: Spec) -> Result<&mut Cryp, Error> {
        match self.specs.iter().position(|s| *s == spec) {
            Some(p) => self.specs.remove(p),
            None => return Err(err_msg("spec not found")),
        };

        Ok(self.calculate_colours())
    }

    fn calculate_colours(&mut self) -> &mut Cryp {
        self.colours = Colours::from_cryp(&self);
        self
    }

    pub fn apply_modifiers(&mut self, team_colours: &Colours) -> &mut Cryp {
        self.specs.sort_unstable();

        self.red_damage.recalculate(&self.specs, team_colours);
        self.red_shield.recalculate(&self.specs, team_colours);
        self.blue_damage.recalculate(&self.specs, team_colours);
        self.blue_shield.recalculate(&self.specs, team_colours);
        self.evasion.recalculate(&self.specs, team_colours);
        self.speed.recalculate(&self.specs, team_colours);
        self.green_damage.recalculate(&self.specs, team_colours);
        self.hp.recalculate(&self.specs, team_colours);

        self
    }

    pub fn is_ko(&self) -> bool {
        self.hp.value == 0
    }

    pub fn immune(&self, skill: Skill) -> Option<Immunity> {
        // also checked in resolve stage so shouldn't happen really
        if self.is_ko() {
           return Some(vec![Effect::Ko]);
        }

        let immunities = self.effects.iter()
            .filter(|e| e.effect.immune(skill))
            .map(|e| e.effect)
            .collect::<Vec<Effect>>();

        if immunities.len() > 0 {
            return Some(immunities);
        }

        None
    }

    pub fn disabled(&self, skill: Skill) -> Option<Disable> {
        if self.is_ko() && !skill.ko_castable() {
           return Some(vec![Effect::Ko]);
        }

        let disables = self.effects.iter()
            .filter(|e| e.effect.disables_skill(skill))
            .map(|e| e.effect)
            .collect::<Vec<Effect>>();

        if disables.len() > 0 {
            return Some(disables);
        }

        None
    }

    pub fn is_stunned(&self) -> bool {
        self.available_skills().len() == 0
    }

    pub fn affected(&self, effect: Effect) -> bool {
        self.effects.iter().any(|s| s.effect == effect)
    }

    pub fn available_skills(&self) -> Vec<&CrypSkill> {
        self.skills.iter()
            .filter(|s| s.cd.is_none())
            .filter(|s| self.disabled(s.skill).is_none())
            .collect()
    }

    pub fn mob_select_skill(&self) -> Option<Skill> {
        let available = self.available_skills();

        if available.len() == 0 {
            return None;
        }

        let highest_cd = available.iter()
            .filter(|s| s.skill.base_cd().is_some())
            .max_by_key(|s| s.skill.base_cd().unwrap());

        return match highest_cd {
            Some(s) => Some(s.skill),
            None => Some(available[0].skill),
        };
    }

    pub fn knows(&self, skill: Skill) -> bool {
        self.skills.iter().any(|s| s.skill == skill)
    }

    pub fn skill_on_cd(&self, skill: Skill) -> Option<&CrypSkill> {
        self.skills.iter().find(|s| s.skill == skill && s.cd.is_some())
    }

    pub fn skill_set_cd(&mut self, skill: Skill) -> &mut Cryp {
        let i = self.skills.iter().position(|s| s.skill == skill).unwrap();
        self.skills.remove(i);
        self.skills.push(CrypSkill::new(skill));

        self
    }

    pub fn reduce_cooldowns(&mut self) -> &mut Cryp {
        for skill in self.skills.iter_mut() {
            // if used cooldown
            if skill.skill.base_cd().is_some() {
                // what is the current cd
                if let Some(current_cd) = skill.cd {

                    // if it's 1 set it to none
                    if current_cd == 1 {
                        skill.cd = None;
                        continue;
                    }

                    // otherwise decrement it
                    skill.cd = Some(current_cd.saturating_sub(1));
                }

            }
        }

        self
    }

    pub fn reduce_effect_durations(&mut self) -> &mut Cryp {
        self.effects = self.effects.clone().into_iter().filter_map(|mut effect| {
            effect.duration = effect.duration.saturating_sub(1);

            if effect.duration == 0 {
                return None;
            }

            // println!("reduced effect {:?}", effect);
            return Some(effect);
        }).collect::<Vec<CrypEffect>>();

        self
    }

    // Stats
    pub fn red_damage(&self) -> u64 {
        let red_damage_mods = self.effects.iter()
            .filter(|e| e.effect.modifications().contains(&Stat::RedDamage))
            .map(|e| (e.effect, e.meta))
            .collect::<Vec<(Effect, Option<EffectMeta>)>>();

        let modified_red_damage = red_damage_mods.iter()
            .fold(self.red_damage.value, |acc, fx| fx.0.apply(acc, fx.1));
        return modified_red_damage;
    }

    pub fn blue_damage(&self) -> u64 {
        let blue_damage_mods = self.effects.iter()
            .filter(|e| e.effect.modifications().contains(&Stat::BlueDamage))
            .map(|e| (e.effect, e.meta))
            .collect::<Vec<(Effect, Option<EffectMeta>)>>();

        let modified_blue_damage = blue_damage_mods.iter()
            .fold(self.blue_damage.value, |acc, fx| fx.0.apply(acc, fx.1));
        return modified_blue_damage;
    }

    pub fn green_damage(&self) -> u64 {
        let green_damage_mods = self.effects.iter()
            .filter(|e| e.effect.modifications().contains(&Stat::GreenDamage))
            .map(|e| (e.effect, e.meta))
            .collect::<Vec<(Effect, Option<EffectMeta>)>>();

        let modified_green_damage = green_damage_mods.iter()
            .fold(self.green_damage.value, |acc, fx| fx.0.apply(acc, fx.1));
        return modified_green_damage;
    }

    pub fn skill_speed(&self, s: Skill) -> u64 {
        self.speed().saturating_mul(s.speed() as u64)
    }

    // todo complete with specs
    pub fn skill_is_aoe(&self, s: Skill) -> bool {
        s.aoe()
    }

    pub fn speed(&self) -> u64 {
        let speed_mods = self.effects.iter()
            .filter(|e| e.effect.modifications().contains(&Stat::Speed))
            .map(|e| (e.effect, e.meta))
            .collect::<Vec<(Effect, Option<EffectMeta>)>>();

        let modified_speed = speed_mods.iter()
            .fold(self.speed.value, |acc, fx| fx.0.apply(acc, fx.1));
        return modified_speed;
    }

    pub fn hp(&self) -> u64 {
        self.hp.value
    }

    fn reduce_hp(&mut self, amount: u64) {
        self.hp.reduce(amount);
        if self.affected(Effect::Clutch) && self.hp() == 0 {
            self.hp.value = 1;
        }
    }

    pub fn recharge(&mut self) -> Event {
        let skill = Skill::Recharge;
        if let Some(immunity) = self.immune(skill) {
            return Event::Immunity {
                skill,
                immunity,
            };
        }

        let red = self.red_shield.max.saturating_sub(self.red_shield.value);
        self.red_shield.value = self.red_shield.max;

        let blue = self.blue_shield.max.saturating_sub(self.blue_shield.value);
        self.blue_shield.value = self.blue_shield.max;

        Event::Recharge { red, blue, skill }
    }

    pub fn deal_green_damage(&mut self, skill: Skill, amount: u64) -> Vec<Event> {
        let mut events = vec![];
        if let Some(immunity) = self.immune(skill) {
            events.push(Event::Immunity {
                immunity,
                skill,
            });
            return events;
        }

        let mods = self.effects.iter()
            .filter(|e| e.effect.modifications().contains(&Stat::GreenDamageTaken))
            .map(|e| (e.effect, e.meta))
            .collect::<Vec<(Effect, Option<EffectMeta>)>>();

        let modified_damage = mods.iter()
            .fold(amount, |acc, fx| fx.0.apply(acc, fx.1));

        match self.affected(Effect::Invert) {
            false => {
                let current_hp = self.hp();
                self.hp.increase(modified_damage);
                let new_hp = self.hp.value;

                let healing = new_hp - current_hp;
                let overhealing = modified_damage - healing;

                events.push(Event::Healing {
                    skill,
                    amount: healing,
                    overhealing,
                });
            },
            true => {
                events.push(Event::Inversion { skill });

                // there is no green shield (yet)
                let current_hp = self.hp();
                self.reduce_hp(modified_damage);
                let delta = current_hp - self.hp();

                events.push(Event::Damage {
                    skill,
                    amount: delta,
                    mitigation: 0,
                    category: Category::GreenDamage,
                });
            }
        }

        return events;
    }

    pub fn deal_red_damage(&mut self, skill: Skill, amount: u64) -> Vec<Event> {
        let mut events = vec![];

        if let Some(immunity) = self.immune(skill) {
            events.push(Event::Immunity {
                skill,
                immunity,
            });
            return events;
        }

        let mods = self.effects.iter()
            .filter(|e| e.effect.modifications().contains(&Stat::RedDamageTaken))
            .map(|e| (e.effect, e.meta))
            .collect::<Vec<(Effect, Option<EffectMeta>)>>();

        let modified_damage = mods.iter()
            .fold(amount, |acc, fx| fx.0.apply(acc, fx.1));

        match self.affected(Effect::Invert) {
            false => {
                // calculate amount of damage red_shield will not absorb
                // eg 50 red_shield 25 damage  ->  0 remainder     25 mitigation
                //    50 red_shield 100 damage ->  50 remainder    50 mitigation
                //    50 red_shield 5 damage   ->  0 remainder     5  mitigation
                let remainder = modified_damage.saturating_sub(self.red_shield.value);
                let mitigation = modified_damage.saturating_sub(remainder);

                // reduce red_shield by mitigation amount
                self.red_shield.reduce(mitigation);

                // deal remainder to hp
                let current_hp = self.hp();
                self.reduce_hp(remainder);
                let delta = current_hp - self.hp();

                events.push(Event::Damage {
                    skill,
                    amount: delta,
                    mitigation,
                    category: Category::RedDamage,
                });
            },
            true => {
                events.push(Event::Inversion { skill });

                let current_hp = self.hp();
                self.hp.increase(modified_damage);
                let new_hp = self.hp.value;
                let healing = new_hp - current_hp;
                let overhealing = modified_damage - healing;

                let current_shield = self.red_shield.value;
                self.red_shield.increase(overhealing);
                let recharge = self.red_shield.value - current_shield;

                if healing > 0 {
                    events.push(Event::Healing {
                        skill,
                        amount: healing,
                        overhealing: overhealing - recharge,
                    });
                }

                if recharge > 0 {
                    events.push(Event::Recharge { red: recharge, blue: 0, skill });
                }
            }
        };

        return events;
    }

    pub fn deal_blue_damage(&mut self, skill: Skill, amount: u64) -> Vec<Event> {
        let mut events = vec![];

        if let Some(immunity) = self.immune(skill) {
            events.push(Event::Immunity {
                skill,
                immunity,
            });
            return events;
        }

        let mods = self.effects.iter()
            .filter(|e| e.effect.modifications().contains(&Stat::BlueDamageTaken))
            .map(|e| (e.effect, e.meta))
            .collect::<Vec<(Effect, Option<EffectMeta>)>>();

        let modified_damage = mods.iter()
            .fold(amount, |acc, fx| fx.0.apply(acc, fx.1));

        match self.affected(Effect::Invert) {
            false => {
                let remainder = modified_damage.saturating_sub(self.blue_shield.value);
                let mitigation = modified_damage.saturating_sub(remainder);

                // reduce blue_shield by mitigation amount
                self.blue_shield.reduce(mitigation);

                // deal remainder to hp
                let current_hp = self.hp();
                self.reduce_hp(remainder);
                let delta = current_hp - self.hp();

                events.push(Event::Damage {
                    skill,
                    amount: delta,
                    mitigation,
                    category: Category::BlueDamage,
                });
            },
            true => {
                events.push(Event::Inversion { skill });

                let current_hp = self.hp();
                self.hp.increase(modified_damage);
                let new_hp = self.hp.value;
                let healing = new_hp - current_hp;
                let overhealing = modified_damage - healing;

                let current_shield = self.blue_shield.value;
                self.blue_shield.increase(overhealing);
                let recharge = self.blue_shield.value - current_shield;

                if healing > 0 {
                    events.push(Event::Healing {
                        skill,
                        amount: healing,
                        overhealing,
                    });
                }

                if recharge > 0 {
                    events.push(Event::Recharge { red: 0, blue: recharge, skill });
                }
            }
        };

        return events;
    }

    pub fn add_effect(&mut self, skill: Skill, effect: CrypEffect) -> Event {
        if let Some(immunity) = self.immune(skill) {
            return Event::Immunity {
                skill,
                immunity,
            };
        }

        // todo modified durations cause of buffs
        let result = Event::Effect {
            effect: effect.effect,
            duration: effect.effect.duration(),
            skill,
        };

        // println!("{:?} {:?} adding effect", self.name, effect.effect);
        self.effects.push(effect);

        return result;
    }

    pub fn evade(&self, skill: Skill) -> Option<Event> {
        if self.evasion.value == 0 {
            return None;
        }

        let mut rng = thread_rng();
        let hp_pct = (self.hp.value * 100) / self.hp.value;
        let evasion_rating = (self.evasion.value * hp_pct) / 100;
        let roll = rng.gen_range(0, 100);
        println!("{:} < {:?}", roll, evasion_rating);

        match roll < evasion_rating {
            true => Some(Event::Evasion {
                skill,
                evasion_rating: evasion_rating,
            }),
            false => None,
        }
    }
}

pub fn cryp_get(tx: &mut Transaction, id: Uuid, account_id: Uuid) -> Result<Cryp, Error> {
    let query = "
        SELECT data
        FROM cryps
        WHERE id = $1
        AND account = $2;
    ";

    let result = tx
        .query(query, &[&id, &account_id])?;

    let result = result.iter().next().ok_or(format_err!("cryp {:} not found", id))?;
    let cryp_bytes: Vec<u8> = result.get(0);
    let cryp = from_slice::<Cryp>(&cryp_bytes).or_else(|_| cryp_recover(cryp_bytes, tx))?;

    return Ok(cryp);
}

pub fn cryp_spawn(params: CrypSpawnParams, tx: &mut Transaction, account: &Account) -> Result<Cryp, Error> {
    let cryp = Cryp::new()
        .named(&params.name)
        .set_account(account.id);

    let cryp_bytes = to_vec(&cryp)?;

    let query = "
        INSERT INTO cryps (id, account, data)
        VALUES ($1, $2, $3)
        RETURNING id, account;
    ";

    let result = tx
        .query(query, &[&cryp.id, &account.id, &cryp_bytes])?;

    let _returned = result.iter().next().ok_or(err_msg("no row returned"))?;

    // println!("{:?} spawned cryp {:}", account.id, cryp.id);

    return Ok(cryp);
}

pub fn cryp_write(cryp: Cryp, tx: &mut Transaction) -> Result<Cryp, Error> {
    let cryp_bytes = to_vec(&cryp)?;

    let query = "
        UPDATE cryps
        SET data = $1
        WHERE id = $2
        RETURNING id, account, data;
    ";

    let result = tx
        .query(query, &[&cryp_bytes, &cryp.id])?;

    let _returned = result.iter().next().expect("no row returned");

    // println!("{:?} wrote cryp", cryp.id);

    return Ok(cryp);
}

pub fn cryp_recover(cryp_bytes: Vec<u8>, tx: &mut Transaction) -> Result<Cryp, Error> {
    let c = from_slice::<CrypRecover>(&cryp_bytes)?;

    let mut cryp = Cryp::new()
        .named(&c.name)
        .set_account(c.account);

    cryp.id = c.id;

    println!("recovered cryp {:?}", c.name);

    return cryp_write(cryp, tx);
}

#[cfg(test)]
mod tests {
  use cryp::*;
  use spec::IntPct;

    #[test]
    fn create_cryp_test() {
        let cryp = Cryp::new()
            .named(&"hatchling".to_string());

        assert_eq!(cryp.name, "hatchling".to_string());
        return;
    }

     #[test]
     fn cryp_colours_test() {
        let mut cryp = Cryp::new()
            .named(&"redboi".to_string());

        cryp.learn_mut(Skill::Strike);
        cryp.spec_add(Spec::LifeI).unwrap();
        cryp.spec_add(Spec::RedDamageI).unwrap();
        cryp.spec_add(Spec::RedDamageI).unwrap();
        cryp.spec_add(Spec::BlueShieldI).unwrap();

        assert_eq!(cryp.colours.red, 6);
        assert_eq!(cryp.colours.green, 2);
        assert_eq!(cryp.colours.blue, 2);

        return;
    }

         #[test]
     fn cryp_team_modifiers_test() {
        let mut cryp = Cryp::new()
            .named(&"team player".to_string());

        cryp.spec_add(Spec::RedDamageI).unwrap();
        cryp.spec_add(Spec::GreenDamageI).unwrap();
        cryp.spec_add(Spec::BlueDamageI).unwrap();

        let team_colours = Colours {
            red: 5,
            green: 15,
            blue: 25,
        };

        cryp.apply_modifiers(&team_colours);

        assert!(cryp.red_damage.value == cryp.red_damage.base + cryp.red_damage.base.pct(10));
        assert!(cryp.green_damage.value == cryp.green_damage.base + cryp.green_damage.base.pct(20));
        assert!(cryp.blue_damage.value == cryp.blue_damage.base + cryp.blue_damage.base.pct(65));

        return;
    }
}
