use rand::prelude::*;
use uuid::Uuid;

// timekeeping
use chrono::prelude::*;
use chrono::Duration;

// Db Commons
use serde_cbor::{from_slice, to_vec};
use postgres::transaction::Transaction;
use failure::Error;
use failure::err_msg;

use account::Account;
use rpc::{GameStateParams, GameSkillParams};
use cryp::{Cryp};
use skill::{Skill, Effect, Cast, Resolution, Event, resolve};
use player::{Player};
use instance::{instance_game_finished, global_game_finished};
use util::{IntPct};

#[derive(Debug,Clone,Copy,PartialEq,Serialize,Deserialize)]
pub enum Phase {
    Start,
    Skill,
    Resolve,
    Finish,
}

#[derive(Debug,Clone,Serialize,Deserialize)]
pub struct Game {
    pub id: Uuid,
    pub player_cryps: usize,
    pub player_num: usize,
    pub players: Vec<Player>,
    pub phase: Phase,
    pub stack: Vec<Cast>,
    pub resolved: Vec<Resolution>,
    pub log: Vec<String>,
    pub instance: Option<Uuid>,
    phase_end: DateTime<Utc>,
}

impl Game {
    pub fn new() -> Game {
        return Game {
            id: Uuid::new_v4(),
            player_cryps: 0,
            player_num: 0,
            players: vec![],
            phase: Phase::Start,
            stack: vec![],
            resolved: vec![],
            log: vec![],
            instance: None,
            phase_end: Utc::now(),
        };
    }

    pub fn set_player_num(&mut self, size: usize) -> &mut Game {
        self.player_num = size;
        self
    }

    pub fn set_player_cryps(&mut self, size: usize) -> &mut Game {
        self.player_cryps = size;
        self
    }

    pub fn set_instance(&mut self, id: Uuid) -> &mut Game {
        self.instance = Some(id);
        self
    }

    pub fn joinable(&self) -> bool {
        self.can_start()
    }

    pub fn player_add(&mut self, mut player: Player) -> Result<&mut Game, Error> {
        if self.players.len() == self.player_num {
            return Err(err_msg("maximum number of players"));
        }

        if self.players.iter().any(|t| t.id == player.id) {
            return Err(err_msg("player already in game"));
        }

        if player.cryps.iter().all(|c| c.skills.len() == 0) {
            println!("WARNING: {:?} has no skills and has forfeited {:?}", player.name, self.id);
            player.forfeit();
        }

        let player_description = player.cryps.iter().map(|c| c.name.clone()).collect::<Vec<String>>().join(", ");
        self.log.push(format!("{:} has joined the game. [{:}]", player.name, player_description));

        self.players.push(player);

        Ok(self)
    }

    // handle missing player properly
    pub fn player_by_id(&mut self, id: Uuid) -> Result<&mut Player, Error> {
        self.players
            .iter_mut()
            .find(|t| t.id == id)
            .ok_or(format_err!("{:?} not in game", id))
    }

    pub fn cryp_by_id(&mut self, id: Uuid) -> Option<&mut Cryp> {
        match self.players.iter_mut().find(|t| t.cryps.iter().any(|c| c.id == id)) {
            Some(player) => player.cryps.iter_mut().find(|c| c.id == id),
            None => None,
        }
    }

    pub fn cryp_by_id_take(&mut self, id: Uuid) -> Cryp {
        match self.players.iter_mut().find(|t| t.cryps.iter().any(|c| c.id == id)) {
            Some(player) => {
                let i = player.cryps.iter().position(|c| c.id == id).unwrap();
                player.cryps.remove(i)
            }
            None => panic!("id not in game {:}", id),
        }
    }


    fn all_cryps(&self) -> Vec<Cryp> {
        self.players.clone()
            .into_iter()
            .flat_map(
                |t| t.cryps
                    .into_iter())
                    .collect::<Vec<Cryp>>()
    }

    fn update_cryp(&mut self, cryp: &mut Cryp) -> &mut Game {
        match self.players.iter_mut().find(|t| t.cryps.iter().any(|c| c.id == cryp.id)) {
            Some(player) => {
                let index = player.cryps.iter().position(|t| t.id == cryp.id).unwrap();
                player.cryps.remove(index);
                player.cryps.push(cryp.clone());
                player.cryps.sort_unstable_by_key(|c| c.id);
            },
            None => panic!("cryp not in game"),
        };

        self
    }

    pub fn can_start(&self) -> bool {
        return self.players.len() == self.player_num
            && self.players.iter().all(|t| t.cryps.len() == self.player_cryps)
    }

    pub fn start(mut self) -> Game {
        self.log.push("Game starting...".to_string());

        // forfeit
        if self.finished() {
            return self.finish();
        }

        self.skill_phase_start()
    }

    fn skill_phase_start(mut self) -> Game {
        self.phase_end = Utc::now()
            .checked_add_signed(Duration::seconds(60))
            .expect("could not set phase end");

        for player in self.players.iter_mut() {
            if player.skills_required() != 0 {
                player.set_ready(false);
            }
        }

        self.log.push("<Skill Phase>".to_string());

        if ![Phase::Start, Phase::Resolve].contains(&self.phase) {
            panic!("game not in Resolve or start phase");
        }

        self.phase = Phase::Skill;

        self.pve_add_skills();

        if self.skill_phase_finished() {
            return self.resolve_phase_start()
        }

        self
    }

    fn pve_add_skills(&mut self) -> &mut Game {
        let mut pve_skills = vec![];

        for mobs in self.players
            .iter()
            .filter(|t| t.bot) {
            let player_player = self.players.iter().find(|t| t.id != mobs.id).unwrap();

            for mob in mobs.cryps.iter() {
                let skill = mob.mob_select_skill();
                // println!("{:?} {:?}", mob.name, skill);
                match skill {
                    Some(s) => {
                        let mut rng = thread_rng();

                        // the mut marks it as being able to be called
                        // more than once
                        let mut find_target = || {
                            match s.defensive() {
                                true => &mobs.cryps[rng.gen_range(0, mobs.cryps.len())],
                                false => &player_player.cryps[rng.gen_range(0, player_player.cryps.len())],
                            }
                        };

                        let mut target = find_target();

                        while target.is_ko() {
                            target = find_target();
                        }

                        pve_skills.push((mobs.id, mob.id, Some(target.id), s));
                    },
                    None => continue,
                };
            }
        }

        for (player_id, mob_id, target_id, s) in pve_skills {
            match self.add_skill(player_id, mob_id, target_id, s) {
                Ok(_) => (),
                Err(e) => {
                    println!("{:?}", self.cryp_by_id(mob_id));
                    panic!("{:?} unable to add pve mob skill {:?}", e, s);
                },
            }

            self.player_ready(player_id).unwrap();
        }

        self
    }

    fn add_skill(&mut self, player_id: Uuid, source_cryp_id: Uuid, target_cryp_id: Option<Uuid>, skill: Skill) -> Result<Uuid, Error> {
        // check player in game
        self.player_by_id(player_id)?;

        if self.phase != Phase::Skill {
            return Err(err_msg("game not in skill phase"));
        }

        let final_target_id = match skill.self_targeting() {
            true => source_cryp_id,
            false => match target_cryp_id {
                Some(t) => t,
                None => return Err(err_msg("skill requires a target")),
            }
        };

        // target checks
        {
            let target = match self.cryp_by_id(final_target_id) {
                Some(c) => c,
                None => return Err(err_msg("target cryp not in game")),
            };

            // fixme for rez
            if target.is_ko() {
               return Err(err_msg("target cryp is ko"));
            }
        }

        // cryp checks
        {
            let cryp = match self.cryp_by_id(source_cryp_id) {
                Some(c) => c,
                None => return Err(err_msg("cryp not in game")),
            };

            if cryp.is_ko() {
               return Err(err_msg("cryp is ko"));
            }

            // check the cryp has the skill
            if !cryp.knows(skill) {
                return Err(err_msg("cryp does not have that skill"));
            }

            if cryp.skill_on_cd(skill).is_some() {
               return Err(err_msg("abiltity on cooldown"));
            }

            // check here as well so uncastable spells don't go on the stack
            if let Some(disable) = cryp.disabled(skill) {
               return Err(format_err!("skill disabled {:?}", disable));
            }
        }

        // replace cryp skill
        if let Some(s) = self.stack.iter_mut().position(|s| s.source_cryp_id == source_cryp_id) {
            self.stack.remove(s);
        }

        let skill = Cast::new(source_cryp_id, player_id, final_target_id, skill);
        let skill_id = skill.id;
        self.stack.push(skill);

        return Ok(skill_id);
    }

    fn player_ready(&mut self, player_id: Uuid) -> Result<&mut Game, Error> {
        if self.phase != Phase::Skill {
            return Err(err_msg("game not in skill phase"));
        }

        self.player_by_id(player_id)?
            .set_ready(true);

        Ok(self)
    }

    fn skill_phase_finished(&self) -> bool {
        self.players.iter().all(|t| t.ready)
        // self.players.iter()
        //     // for every player
        //     .all(|t| self.stack.iter()
        //         // the number of skills they have cast
        //         .filter(|s| s.source_player_id == t.id).collect::<Vec<&Cast>>()
        //         // should equal the number required this turn
        //         .len() == t.skills_required()
        //     )
    }

    // requires no input
    // just do it
    fn resolve_phase_start(mut self) -> Game {
        if self.phase != Phase::Skill {
            panic!("game not in skill phase");
        }
        assert!(self.skill_phase_finished());

        self.phase = Phase::Resolve;
        self.log.push("<Resolve Phase>".to_string());

        self.resolve_skills()
    }

    fn stack_sort_speed(&mut self) -> &mut Game {
        let mut sorted = self.stack.clone();
        sorted.iter_mut()
            .for_each(|s| {
                let caster = self.cryp_by_id(s.source_cryp_id).unwrap();
                let speed = caster.skill_speed(s.skill);
                s.speed = speed;
            });

        sorted.sort_unstable_by_key(|s| s.speed);

        self.stack = sorted;

        self
    }

    fn cryp_aoe_targets(&self, cryp_id: Uuid) -> Vec<Uuid> {
        self.players.iter()
            .find(|t| t.cryps.iter().any(|c| c.id == cryp_id))
            .unwrap()
            .cryps
            .iter()
            .map(|c| c.id)
            .collect()
    }

    fn get_targets(&self, skill: Skill, source: &Cryp, target_cryp_id: Uuid) -> Vec<Uuid> {
        let target_player = self.players.iter()
            .find(|t| t.cryps.iter().any(|c| c.id == target_cryp_id))
            .unwrap();

        if let Some(t) = target_player.taunting() {
            return vec![t.id];
        }

        match source.skill_is_aoe(skill) {
            true => self.cryp_aoe_targets(target_cryp_id),
            false => vec![target_cryp_id],
        }
    }

    fn resolve_skills(mut self) -> Game {
        if self.phase != Phase::Resolve {
            panic!("game not in Resolve phase");
        }

        // find their statuses with ticks
        let mut ticks = self.all_cryps()
            .iter()
            .flat_map(
                |c| c.effects
                    .iter()
                    .cloned()
                    .filter_map(|e| e.tick))
                    .collect::<Vec<Cast>>();

        // add them to the stack
        self.stack.append(&mut ticks);

        self.stack_sort_speed();

        // temp vec of this round's resolving skills
        // because need to check cooldown use before pushing them into the complete list
        let mut casts = vec![];

        while let Some(cast) = self.stack.pop() {
            // println!("{:} casts ", cast);

            let mut resolutions = vec![];
            let mut source = self.cryp_by_id(cast.source_cryp_id).unwrap().clone();

            let targets = self.get_targets(cast.skill, &source, cast.target_cryp_id);
            for target_id in targets {
                let mut source = self.cryp_by_id(cast.source_cryp_id).unwrap().clone();
                let mut target = self.cryp_by_id(target_id).unwrap().clone();
                resolutions = resolve(cast.skill, &mut source, &mut target, resolutions);
                // save the clones
                self.update_cryp(&mut source);
                self.update_cryp(&mut target);
            }

            resolutions.reverse();
            while let Some(resolution) = resolutions.pop() {
                self.log_resolution(cast.speed, &resolution);
                // the results go into the resolutions
                self.resolved.push(resolution);
            }

            // the cast itself goes into this temp vec
            // to handle cooldowns
            casts.push(cast);

            // sort the stack again in case speeds have changed
            self.stack_sort_speed();
        };

        // println!("{:#?}", self.casts);

        // handle cooldowns and statuses
        self.progress_durations(&casts);

        if self.finished() {
            return self.finish()
        }

        self.skill_phase_start()
    }

    fn progress_durations(&mut self, resolved: &Vec<Cast>) -> &mut Game {
        for mut cryp in self.all_cryps() {
            // println!("progressing durations for {:}", cryp.name);

            if cryp.is_ko() {
                continue;
            }

            // only reduce cooldowns if no cd was used
            // have to borrow self for the skill check
            {
                if let Some(skill) = resolved.iter().find(|s| s.source_cryp_id == cryp.id) {
                    if skill.used_cooldown() {
                        cryp.skill_set_cd(skill.skill);
                    } else {
                        cryp.reduce_cooldowns();
                    }
                } else {
                   cryp.reduce_cooldowns();
                }
            }

            // always reduce durations
            cryp.reduce_effect_durations();
            self.update_cryp(&mut cryp);
        }

        self
    }

    fn log_resolution(&mut self, speed: u64, resolution: &Resolution) -> &mut Game {
        let Resolution { source, target, event } = resolution;
        match event {
            Event::Ko { skill: _ }=>
                self.log.push(format!("{:} KO!", target.name)),

            Event::Disable { skill, disable } =>
                self.log.push(format!("{:} {:?} {:} disabled {:?}",
                    source.name, skill, target.name, disable)),

            Event::Immunity { skill, immunity } =>
                self.log.push(format!("[{:}] {:} {:?} {:} immune {:?}",
                    speed, source.name, skill, target.name, immunity)),

            Event::TargetKo { skill } =>
                self.log.push(format!("[{:}] {:} {:?} {:} - target is KO",
                    speed, source.name, skill, target.name)),

            Event::Damage { skill, amount, mitigation, colour: _ } =>
                self.log.push(format!("[{:}] {:} {:?} {:} {:} ({:} mitigated)",
                    speed, source.name, skill, target.name, amount, mitigation)),

            Event::Healing { skill, amount, overhealing } =>
                self.log.push(format!("[{:}] {:} {:?} {:} {:} healing ({:}OH)",
                    speed, source.name, skill, target.name, amount, overhealing)),

            Event::Inversion { skill } =>
                self.log.push(format!("[{:}] {:} {:?} {:} INVERTED",
                    speed, source.name, skill, target.name)),

            Event::Reflection { skill } =>
                self.log.push(format!("[{:}] {:} {:?} {:} REFLECTED",
                    speed, source.name, skill, target.name)),

            Event::Effect { skill, effect, duration } =>
                self.log.push(format!("[{:}] {:} {:?} {:} {:?} {:}T",
                    speed, source.name, skill, target.name, effect, duration)),

            Event::Skill { skill } =>
                self.log.push(format!("[{:}] {:} {:?} {:}",
                    speed, source.name, skill, target.name)),

            Event::Removal { effect } =>
                self.log.push(format!("[{:}] {:?} removed {:} {:?}",
                    speed, source.name, target.name, effect)),

            Event::Recharge { skill, red, blue } =>
                self.log.push(format!("[{:}] {:} {:?} {:} {:}R {:}B",
                    speed, source.name, skill, target.name, red, blue)),

            Event::Evasion { skill, evasion_rating } =>
                self.log.push(format!("[{:}] {:} {:?} {:} evaded ({:}%)",
                    speed, source.name, skill, target.name, evasion_rating)),

            Event::Incomplete => panic!("incomplete resolution {:?}", resolution),
        }

        self
    }

    pub fn finished(&self) -> bool {
        self.players.iter().any(|t| t.cryps.iter().all(|c| c.is_ko()))
    }

    pub fn winner(&self) -> Option<&Player> {
        self.players.iter().find(|t| t.cryps.iter().any(|c| !c.is_ko()))
    }

    fn finish(mut self) -> Game {
        self.phase = Phase::Finish;
        self.log.push(format!("Game finished."));

        {
            let winner = self.players.iter().find(|t| t.cryps.iter().any(|c| !c.is_ko()));
            match winner {
                Some(w) => self.log.push(format!("Winner: {:}", w.name)),
                None => self.log.push(format!("Game was drawn.")),
            };
        }

        self
    }

    fn phase_timed_out(&self) -> bool {
        Utc::now().signed_duration_since(self.phase_end).num_milliseconds() > 0
    }

    pub fn upkeep(mut self) -> Game {
        if self.phase == Phase::Finish {
            return self;
        }

        println!("upkeep beginning: {:} vs {:}", self.players[0].name, self.players[1].name);

        if !self.phase_timed_out() {
            return self;
        }

        for player in self.players.iter_mut() {
            if !player.ready {
                player.set_ready(true);
                player.add_warning();
                println!("upkeep: {:} warned", player.name);
                if player.warnings >= 3 {
                    player.forfeit();
                    println!("upkeep: {:} forfeited", player.name);
                    self.log.push(format!("{:} forfeited.", player.name));
                }
            }
        }

        self = self.resolve_phase_start();
        self
    }
}

pub fn game_write(tx: &mut Transaction, game: &Game) -> Result<(), Error> {
    let game_bytes = to_vec(&game)?;

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

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

    result.iter().next().ok_or(format_err!("no game written"))?;

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

    return Ok(());
}

pub fn game_state(params: GameStateParams, tx: &mut Transaction, _account: &Account) -> Result<Game, Error> {
    return game_get(tx, params.id)
}

pub fn game_get(tx: &mut Transaction, id: Uuid) -> Result<Game, Error> {
    let query = "
        SELECT *
        FROM games
        WHERE id = $1
        FOR UPDATE;
    ";

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

    let returned = match result.iter().next() {
        Some(row) => row,
        None => return Err(err_msg("game not found")),
    };

    // tells from_slice to cast into a cryp
    let game_bytes: Vec<u8> = returned.get("data");
    let game = from_slice::<Game>(&game_bytes)?;

    return Ok(game);
}

pub fn games_need_upkeep(tx: &mut Transaction) -> Result<Vec<Game>, Error> {
    // let query = "
    //     SELECT data, id
    //     FROM games
    //     WHERE updated_at < now() - interval '5 seconds'
    //     AND finished = false;
    // ";

    let query = "
        SELECT data, id
        FROM games
        WHERE finished = false
        FOR UPDATE;
    ";
    let result = tx
        .query(query, &[])?;

    let mut list = vec![];

    for row in result.into_iter() {
        let bytes: Vec<u8> = row.get(0);
        let id = row.get(1);

        match from_slice::<Game>(&bytes) {
            Ok(i) => list.push(i),
            Err(_e) => {
                game_delete(tx, id)?;
            }
        };
    }

    return Ok(list);
}

pub fn game_delete(tx: &mut Transaction, id: Uuid) -> Result<(), Error> {
    let query = "
        DELETE
        FROM games
        WHERE id = $1;
    ";

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

    if result != 1 {
        return Err(format_err!("unable to delete player {:?}", id));
    }

    println!("game deleted {:?}", id);

    return Ok(());
}

// pub fn game_global_startup(tx: &mut Transaction) -> Result<(), Error> {
//     if game_global_get(tx).is_ok() {
//         println!("global mm game exists");
//         return Ok(());
//     }

//     let mut game = Game::new();

//     game
//         .set_player_num(2)
//         .set_player_cryps(3)
//         .set_mode(GameMode::Pvp);

//     game_write(tx, &game)?;

//     let query = "
//         INSERT INTO matchmaking (id, game)
//         VALUES ($1, $2)
//         RETURNING id;
//     ";

//     let result = tx
//         .query(query, &[&Uuid::nil(), &game.id])?;

//     result.iter().next().ok_or(format_err!("no game written"))?;

//     println!("{:} wrote global mm startup", game.id);

//     return Ok(());
// }

// pub fn game_global_set(tx: &mut Transaction, game: &Game) -> Result<(), Error> {
//     let query = "
//         UPDATE matchmaking
//         SET game = $1
//         WHERE id = $2
//         RETURNING id, game;
//     ";

//     let result = tx
//         .query(query, &[&game.id, &Uuid::nil()])?;

//     result.iter()
//         .next()
//         .ok_or(err_msg("could not set global game mm"))?;

//     return Ok(());
// }

// pub fn game_global_get(tx: &mut Transaction) -> Result<Game, Error> {
//     let query = "
//         SELECT * from games
//         WHERE id = (
//             SELECT game
//             FROM matchmaking
//             WHERE id = $1
//         );
//     ";

//     let delete_query = "
//         DELETE from matchmaking;
//     ";

//     let result = tx
//         .query(query, &[&Uuid::nil()])?;

//     let returned = match result.iter().next() {
//         Some(row) => row,
//         None => return Err(err_msg("game not found")),
//     };

//     // tells from_slice to cast into a cryp
//     let game_bytes: Vec<u8> = returned.get("data");
//     let game = match from_slice::<Game>(&game_bytes) {
//         Ok(g) => g,
//         Err(_) => {
//             tx.query(delete_query, &[])?;
//             return Err(err_msg("matchmaking game was invalid"))
//         }
//     };

//     return Ok(game);
// }


pub fn game_update(tx: &mut Transaction, game: &Game) -> Result<(), Error> {
    let game_bytes = to_vec(&game)?;

    let query = "
        UPDATE games
        SET data = $1, finished = $2, updated_at = now()
        WHERE id = $3
        RETURNING id, data;
    ";

    let result = tx
        .query(query, &[&game_bytes, &game.finished(), &game.id])?;

    result.iter().next().ok_or(format_err!("game {:?} could not be written", game))?;

    if game.finished() {
        if let Some(i) = game.instance {
            match i == Uuid::nil() {
                true => global_game_finished(tx, &game)?,
                false => instance_game_finished(tx, &game, i)?,
            }
        }
    }

    return Ok(());
}

pub fn game_skill(params: GameSkillParams, tx: &mut Transaction, account: &Account) -> Result<Game, Error> {
    let mut game = game_get(tx, params.game_id)?;

    game.add_skill(account.id, params.cryp_id, params.target_cryp_id, params.skill)?;

    if game.skill_phase_finished() {
        game = game.resolve_phase_start();
    }

    game_update(tx, &game)?;

    Ok(game)
}

pub fn game_ready(params: GameStateParams, tx: &mut Transaction, account: &Account) -> Result<Game, Error> {
    let mut game = game_get(tx, params.id)?;

    game.player_ready(account.id)?;

    if game.skill_phase_finished() {
        game = game.resolve_phase_start();
    }

    game_update(tx, &game)?;

    Ok(game)
}

// pub fn game_pve_new(cryp_ids: Vec<Uuid>, mode: GameMode, tx: &mut Transaction, account: &Account) -> Result<Game, Error> {
//     if cryp_ids.len() == 0 {
//         return Err(err_msg("no cryps selected"));
//     }

//     let cryps = cryp_ids
//         .iter()
//         .map(|id| cryp_get(tx, *id, account.id))
//         .collect::<Result<Vec<Cryp>, Error>>()?;

//     if cryps.len() > 3 {
//         return Err(err_msg("player size too large (3 max)"));
//     }

//     // create the game
//     let mut game = Game::new();
//     // let game_id = game.id;

//     game;
//         .set_player_num(2)
//         .set_player_cryps(cryps.len())
//         .set_mode(mode);

//     // create the mob player
//     let mob_player = generate_mob_player(mode, &cryps);

//     // add the players
//     let mut plr_player = Player::new(account.id);
//     plr_player
//         .set_cryps(cryps);


//     game
//         .player_add(plr_player)?
//         .player_add(mob_player)?;

//     game.start();

//     return Ok(game);
// }

// pub fn game_pve(params: GamePveParams, tx: &mut Transaction, account: &Account) -> Result<Game, Error> {
//     let game = game_pve_new(params.cryp_ids, GameMode::Normal, tx, account)?;

//     // persist
//     game_write(tx, &game)?;

//     Ok(game)
// }

pub fn game_instance_new(tx: &mut Transaction, players: Vec<Player>, game_id: Uuid, instance_id: Uuid) -> Result<Game, Error> {
    // create the game
    let mut game = Game::new();
    game.id = game_id;

    game
        .set_player_num(2)
        .set_player_cryps(3)
        .set_instance(instance_id);

    // create the initiators player
    for player in players {
        game.player_add(player)?;
    }

    if game.can_start() {
        game = game.start();
    }

    // persist
    game_write(tx, &game)?;

    Ok(game)
}

pub fn game_instance_join(tx: &mut Transaction, player: Player, game_id: Uuid) -> Result<Game, Error> {
    let mut game = game_get(tx, game_id)?;

    game.player_add(player)?;

    if game.can_start() {
        game = game.start();
    }

    println!("{:?} game joined", game.id);

    game_update(tx, &game)?;

    Ok(game)
}

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

    fn create_test_game() -> Game {
        let mut x = Cryp::new()
            .named(&"pronounced \"creeep\"".to_string())
            .learn(Skill::Attack)
            .learn(Skill::TestStun)
            .learn(Skill::TestTouch)
            .learn(Skill::TestBlock)
            .learn(Skill::TestParry)
            .learn(Skill::TestSiphon)
            .learn(Skill::Amplify)
            .learn(Skill::Stun)
            .learn(Skill::Block);

        let mut y = Cryp::new()
            .named(&"lemongrass tea".to_string())
            .learn(Skill::Attack)
            .learn(Skill::TestStun)
            .learn(Skill::TestTouch)
            .learn(Skill::TestBlock)
            .learn(Skill::TestParry)
            .learn(Skill::TestSiphon)
            .learn(Skill::Amplify)
            .learn(Skill::Stun)
            .learn(Skill::Block);

        let mut game = Game::new();

        game
            .set_player_num(2)
            .set_player_cryps(1);

        let x_player_id = Uuid::new_v4();
        x.account = x_player_id;
        let mut x_player = Player::new(x_player_id, &"ntr".to_string(), vec![x]);

        let y_player_id = Uuid::new_v4();
        y.account = y_player_id;
        let mut y_player = Player::new(y_player_id, &"mash".to_string(), vec![y]);

        game
            .player_add(x_player).unwrap()
            .player_add(y_player).unwrap();

        assert!(game.can_start());

        return game.start();
    }

    fn create_2v2_test_game() -> Game {
        let mut i = Cryp::new()
            .named(&"pretaliate".to_string())
            .learn(Skill::Attack)
            .learn(Skill::TestTouch);

        let mut j = Cryp::new()
            .named(&"poy sian".to_string())
            .learn(Skill::Attack)
            .learn(Skill::TestTouch);

        let mut x = Cryp::new()
            .named(&"pronounced \"creeep\"".to_string())
            .learn(Skill::Attack)
            .learn(Skill::TestTouch);

        let mut y = Cryp::new()
            .named(&"lemongrass tea".to_string())
            .learn(Skill::Attack)
            .learn(Skill::TestTouch);

        let mut game = Game::new();

        game
            .set_player_num(2)
            .set_player_cryps(2);

        let i_player_id = Uuid::new_v4();
        i.account = i_player_id;
        j.account = i_player_id;
        let i_player = Player::new(i_player_id, &"ntr".to_string(), vec![i, j]);

        let x_player_id = Uuid::new_v4();
        x.account = x_player_id;
        y.account = x_player_id;
        let x_player = Player::new(x_player_id, &"mashy".to_string(), vec![x, y]);

        game
            .player_add(i_player).unwrap()
            .player_add(x_player).unwrap();

        assert!(game.can_start());

        return game.start();
    }

    #[test]
    fn phase_test() {
        let mut game = create_test_game();

        let x_player = game.players[0].clone();
        let y_player = game.players[1].clone();

        let x_cryp = x_player.cryps[0].clone();
        let y_cryp = y_player.cryps[0].clone();

        game.add_skill(x_player.id, x_cryp.id, Some(y_cryp.id), Skill::Attack).unwrap();
        game.add_skill(y_player.id, y_cryp.id, Some(x_cryp.id), Skill::Attack).unwrap();

        game.player_ready(x_player.id).unwrap();
        game.player_ready(y_player.id).unwrap();

        assert!(game.skill_phase_finished());

        game = game.resolve_phase_start();

        assert!([Phase::Skill, Phase::Finish].contains(&game.phase));

        return;
    }

    #[test]
    fn stun_test() {
        let mut game = create_test_game();

        let x_player = game.players[0].clone();
        let y_player = game.players[1].clone();

        let x_cryp = x_player.cryps[0].clone();
        let y_cryp = y_player.cryps[0].clone();

        let _x_stun_id = game.add_skill(x_player.id, x_cryp.id, Some(y_cryp.id), Skill::TestStun).unwrap();
        game.add_skill(y_player.id, y_cryp.id, Some(x_cryp.id), Skill::TestTouch).unwrap();

        game.player_ready(x_player.id).unwrap();
        game.player_ready(y_player.id).unwrap();

        assert!(game.skill_phase_finished());
        game = game.resolve_phase_start();

        // should auto progress back to skill phase
        assert!(game.phase == Phase::Skill);

        // assert!(game.player_by_id(y_player.id).cryps[0].is_stunned());
        // assert!(game.player_by_id(y_player.id).skills_required() == 0);
    }

    #[test]
    fn ko_resolution_test() {
        let mut game = create_test_game();

        let x_player = game.players[0].clone();
        let y_player = game.players[1].clone();

        let x_cryp = x_player.cryps[0].clone();
        let y_cryp = y_player.cryps[0].clone();

        game.player_by_id(y_player.id).unwrap().cryp_by_id(y_cryp.id).unwrap().red_damage.force(1000000000);
        game.player_by_id(y_player.id).unwrap().cryp_by_id(y_cryp.id).unwrap().speed.force(1000000000);

        // just in case
        // remove all mitigation
        game.player_by_id(x_player.id).unwrap().cryp_by_id(x_cryp.id).unwrap().red_life.force(0);

        let _x_stun_id = game.add_skill(x_player.id, x_cryp.id, Some(y_cryp.id), Skill::TestStun).unwrap();
        game.add_skill(y_player.id, y_cryp.id, Some(x_cryp.id), Skill::Attack).unwrap();

        game.player_ready(x_player.id).unwrap();
        game.player_ready(y_player.id).unwrap();

        assert!(game.skill_phase_finished());
        game = game.resolve_phase_start();

        assert!(!game.player_by_id(y_player.id).unwrap().cryps[0].is_stunned());
        assert!(game.phase == Phase::Finish);
    }

    #[test]
    fn cooldown_test() {
        let mut game = create_test_game();

        let x_player = game.players[0].clone();
        let y_player = game.players[1].clone();

        let x_cryp = x_player.cryps[0].clone();
        let y_cryp = y_player.cryps[0].clone();

        // should auto progress back to skill phase
        assert!(game.phase == Phase::Skill);

        assert!(game.player_by_id(y_player.id).unwrap().cryps[0].skill_on_cd(Skill::Block).is_none());
        assert!(game.player_by_id(y_player.id).unwrap().cryps[0].skill_on_cd(Skill::Stun).is_some());
        assert!(game.player_by_id(x_player.id).unwrap().cryps[0].skill_on_cd(Skill::Block).is_none());

        game.add_skill(x_player.id, x_cryp.id, Some(y_cryp.id), Skill::TestTouch).unwrap();
        game.add_skill(y_player.id, y_cryp.id, Some(x_cryp.id), Skill::TestTouch).unwrap();

        game.player_ready(x_player.id).unwrap();
        game.player_ready(y_player.id).unwrap();

        game = game.resolve_phase_start();

        // should auto progress back to skill phase
        assert!(game.phase == Phase::Skill);
        assert!(game.player_by_id(y_player.id).unwrap().cryps[0].skill_on_cd(Skill::Stun).is_none());

        // second round
        // now we block and it should go back on cd
        let _x_block_id = game.add_skill(x_player.id, x_cryp.id, Some(y_cryp.id), Skill::Stun).unwrap();
        let _y_touch_id = game.add_skill(y_player.id, y_cryp.id, Some(x_cryp.id), Skill::TestTouch).unwrap();

        game.player_ready(x_player.id).unwrap();
        game.player_ready(y_player.id).unwrap();

        game = game.resolve_phase_start();

        assert!(game.player_by_id(x_player.id).unwrap().cryps[0].skill_on_cd(Skill::Stun).is_some());
        assert!(game.player_by_id(y_player.id).unwrap().cryps[0].skill_on_cd(Skill::Block).is_none());
    }

    #[test]
    fn parry_test() {
        let mut game = create_test_game();

        let x_player = game.players[0].clone();
        let y_player = game.players[1].clone();

        let x_cryp = x_player.cryps[0].clone();
        let y_cryp = y_player.cryps[0].clone();

        let _x_block_id = game.add_skill(x_player.id, x_cryp.id, None, Skill::TestParry).unwrap();
        game.add_skill(y_player.id, y_cryp.id, Some(x_cryp.id), Skill::TestStun).unwrap();

        game.player_ready(x_player.id).unwrap();
        game.player_ready(y_player.id).unwrap();

        game = game.resolve_phase_start();

        // should not be stunned because of parry
        assert!(game.player_by_id(x_player.id).unwrap().cryps[0].is_stunned() == false);
        // riposte
        assert!(game.player_by_id(y_player.id).unwrap().cryps[0].green_life() == (1024 - x_cryp.red_damage().pct(Skill::Riposte.multiplier())));
    }

    #[test]
    fn aoe_test() {
        let mut game = create_2v2_test_game();

        let i_player = game.players[0].clone();
        let x_player = game.players[1].clone();

        let i_cryp = i_player.cryps[0].clone();
        let j_cryp = i_player.cryps[1].clone();
        let x_cryp = x_player.cryps[0].clone();
        let y_cryp = x_player.cryps[1].clone();

        game.cryp_by_id(x_cryp.id).unwrap().learn_mut(Skill::Ruin);

        while game.cryp_by_id(x_cryp.id).unwrap().skill_on_cd(Skill::Ruin).is_some() {
            game.cryp_by_id(x_cryp.id).unwrap().reduce_cooldowns();
        }

        game.add_skill(i_player.id, i_cryp.id, Some(x_cryp.id), Skill::TestTouch).unwrap();
        game.add_skill(i_player.id, j_cryp.id, Some(x_cryp.id), Skill::TestTouch).unwrap();
        game.add_skill(x_player.id, x_cryp.id, Some(i_cryp.id), Skill::Ruin).unwrap();
        game.add_skill(x_player.id, y_cryp.id, Some(i_cryp.id), Skill::TestTouch).unwrap();

        game.player_ready(i_player.id).unwrap();
        game.player_ready(x_player.id).unwrap();

        assert!(game.skill_phase_finished());
        game = game.resolve_phase_start();
        game.resolved.remove(0);
        let ruins = game.resolved
            .into_iter()
            .filter(|r| {
                let Resolution { source, target: _, event } = r;
                match source.id == x_cryp.id {
                    true => match event {
                        Event::Effect { effect, duration, skill: _ } => {
                            assert!(*effect == Effect::Ruin);
                            assert!(*duration == 1);
                            true
                        }
                        _ => panic!("ruin result not effect {:?}", event),
                    }
                    false => false,
                }
            })
            .count();

        assert!(ruins == 2);
    }

    #[test]
    fn taunt_test() {
        let mut game = create_2v2_test_game();

        let i_player = game.players[0].clone();
        let x_player = game.players[1].clone();

        let i_cryp = i_player.cryps[0].clone();
        let j_cryp = i_player.cryps[1].clone();
        let x_cryp = x_player.cryps[0].clone();
        let y_cryp = x_player.cryps[1].clone();

        game.cryp_by_id(x_cryp.id).unwrap().learn_mut(Skill::Taunt);

        while game.cryp_by_id(x_cryp.id).unwrap().skill_on_cd(Skill::Taunt).is_some() {
            game.cryp_by_id(x_cryp.id).unwrap().reduce_cooldowns();
        }

        game.add_skill(i_player.id, i_cryp.id, Some(x_cryp.id), Skill::TestTouch).unwrap();
        game.add_skill(i_player.id, j_cryp.id, Some(x_cryp.id), Skill::TestTouch).unwrap();
        game.add_skill(x_player.id, x_cryp.id, Some(i_cryp.id), Skill::Taunt).unwrap();
        game.add_skill(x_player.id, y_cryp.id, Some(i_cryp.id), Skill::TestTouch).unwrap();

        game.player_ready(i_player.id).unwrap();
        game.player_ready(x_player.id).unwrap();

        game = game.resolve_phase_start();

        assert!(game.resolved.len() == 4);
        while let Some(r) = game.resolved.pop() {
            let Resolution { source , target, event: _ } = r;
            if [i_cryp.id, j_cryp.id].contains(&source.id) {
                assert!(target.id == x_cryp.id);
            }
        }
    }

    #[test]
    fn ko_pve_test() {
        let mut game = create_2v2_test_game();

        let i_player = game.players[0].clone();
        let x_player = game.players[1].clone();

        let i_cryp = i_player.cryps[0].clone();
        let j_cryp = i_player.cryps[1].clone();
        let x_cryp = x_player.cryps[0].clone();
        let y_cryp = x_player.cryps[1].clone();

        game.add_skill(i_player.id, i_cryp.id, Some(x_cryp.id), Skill::TestTouch).unwrap();
        game.add_skill(i_player.id, j_cryp.id, Some(x_cryp.id), Skill::TestTouch).unwrap();
        game.add_skill(x_player.id, x_cryp.id, Some(i_cryp.id), Skill::TestTouch).unwrap();
        game.add_skill(x_player.id, y_cryp.id, Some(i_cryp.id), Skill::TestTouch).unwrap();

        game.player_ready(i_player.id).unwrap();
        game.player_ready(x_player.id).unwrap();

        assert!(game.skill_phase_finished());
        game = game.resolve_phase_start();

        assert!([Phase::Skill, Phase::Finish].contains(&game.phase));

        // kill a cryp
        game.player_by_id(i_player.id).unwrap().cryp_by_id(i_cryp.id).unwrap().green_life.reduce(u64::max_value());

        assert!(game.player_by_id(i_player.id).unwrap().skills_required() == 1);
        assert!(game.player_by_id(x_player.id).unwrap().skills_required() == 2);

        // add some more skills
        game.add_skill(i_player.id, j_cryp.id, Some(x_cryp.id), Skill::TestTouch).unwrap();
        game.add_skill(x_player.id, x_cryp.id, Some(j_cryp.id), Skill::TestTouch).unwrap();
        game.add_skill(x_player.id, y_cryp.id, Some(j_cryp.id), Skill::TestTouch).unwrap();
        assert!(game.add_skill(x_player.id, x_cryp.id, Some(i_cryp.id), Skill::TestTouch).is_err());

        game.player_ready(i_player.id).unwrap();
        game.player_ready(x_player.id).unwrap();

        assert!(game.skill_phase_finished());
        game = game.resolve_phase_start();

        assert!(game.player_by_id(i_player.id).unwrap().skills_required() == 1);
        assert!(game.player_by_id(x_player.id).unwrap().skills_required() == 2);
        return;
    }

    #[test]
    fn upkeep_test() {
        let mut game = create_2v2_test_game();
        game.players[0].set_ready(true);
        game.phase_end = Utc::now().checked_sub_signed(Duration::seconds(61)).unwrap();
        game = game.upkeep();
        assert!(game.players[1].warnings == 1);
    }
}
