use crate::{Map, Monster, Position, RunState, Seek, Viewshed, WantsToMelee};
use rltk::Point;
use specs::prelude::*;

pub struct MonsterAI;

impl<'a> System<'a> for MonsterAI {
    #[allow(clippy::type_complexity)]
    type SystemData = (
        ReadExpect<'a, Point>,
        ReadExpect<'a, Entity>,
        ReadExpect<'a, RunState>,
        Entities<'a>,
        ReadStorage<'a, Viewshed>,
        ReadStorage<'a, Monster>,
        WriteStorage<'a, Position>,
        WriteStorage<'a, WantsToMelee>,
        WriteStorage<'a, Seek>,
    );

    fn run(&mut self, data: Self::SystemData) {
        let (
            player_pos,
            player_entity,
            runstate,
            entities,
            viewshed,
            monster,
            position,
            mut wants_to_melee,
            mut seek,
        ) = data;

        if *runstate != RunState::MonsterTurn {
            return;
        }

        for (entity, viewshed, _monster, pos) in (&entities, &viewshed, &monster, &position).join()
        {
            let distance =
                rltk::DistanceAlg::Pythagoras.distance2d(Point::new(pos.x, pos.y), *player_pos);
            if distance < 1.5 {
                wants_to_melee
                    .insert(
                        entity,
                        WantsToMelee {
                            target: *player_entity,
                        },
                    )
                    .expect("Unable to insert attack");
            } else if viewshed.visible_tiles.contains(&*player_pos) {
                seek.insert(
                    entity,
                    Seek {
                        tgt_x: player_pos.x,
                        tgt_y: player_pos.y,
                    },
                )
                .expect("Unable to insert seek");
            }
        }
    }
}

pub struct MoveFollow;

impl<'a> System<'a> for MoveFollow {
    type SystemData = (
        WriteExpect<'a, Map>,
        WriteStorage<'a, Position>,
        WriteStorage<'a, Seek>,
        WriteStorage<'a, Viewshed>,
    );

    fn run(&mut self, (mut map, mut position, mut seek, mut viewshed): Self::SystemData) {
        for (mut pos, seek, mut view) in (&mut position, &seek, &mut viewshed).join() {
            let path = rltk::a_star_search(
                map.xy_idx(pos.x, pos.y) as i32,
                map.xy_idx(seek.tgt_x, seek.tgt_y) as i32,
                &mut *map,
            );
            if path.success && path.steps.len() > 1 {
                let mut idx = map.xy_idx(pos.x, pos.y);
                map.blocked[idx] = false;
                pos.x = path.steps[1] % map.width;
                pos.y = path.steps[1] / map.width;
                idx = map.xy_idx(pos.x, pos.y);
                map.blocked[idx] = true;
                view.dirty = true;
            }
        }

        seek.clear();
    }
}
