import tcod as libtcod
from random import randint
from message_log import Message

class BasicMonster:
    def __init__(self):
        self.owner = None

    def take_turn(self, target, fov_map, game_map, entities):
        results = []
        monster = self.owner
        if libtcod.map_is_in_fov(fov_map, monster.x, monster.y):
            if monster.distance_to(target) >= 2:
                monster.move_astar(target, entities, game_map)
            elif target.fighter.hp > 0:
                if monster.fighter:
                    attack_results = monster.fighter.attack(target)
                    results.extend(attack_results)
        return results

class SummonerMonster(BasicMonster):
    def __init__(self, chance=30, summon="goblin"):
        self.owner = None
        self.chance = chance
        self.summon = summon

    def take_turn(self, target, fov_map, game_map, entities):
        level = game_map.dungeon_level - 1
        monster = self.owner
        if libtcod.map_is_in_fov(fov_map, monster.x, monster.y):
            if randint(0, 100) < self.chance:
                return [{
                    'summon': {'monster': self.summon, 'level': level},
                    'message': Message('%s has summoned a %s' % (monster.name, self.summon), libtcod.purple)
                }]
            else:
                return super().take_turn(target, fov_map, game_map, entities)
        return []


class ParalysedMonster(BasicMonster):
    def __init__(self, previous_ai, number_of_turns=5):
        self.previous_ai = previous_ai
        self.number_of_turns = number_of_turns

    def take_turn(self, target, fov_map, game_map, entities):
        results = []
        if self.number_of_turns > 0:
            self.number_of_turns -= 1
        else:
            self.owner.ai = self.previous_ai
            results.append({
                'message': Message('%s is no longer confused' % (self.owner.name), libtcod.light_yellow)
            })
        return results

class ConfusedMonster(BasicMonster):
    def __init__(self, previous_ai, number_of_turns=10):
        self.previous_ai = previous_ai
        self.number_of_turns = number_of_turns

    def take_turn(self, target, fov_map, game_map, entities):
        results = []

        if self.number_of_turns > 0:
            random_x = self.owner.x + randint(0, 2) - 1
            random_y = self.owner.y + randint(0, 2) - 1

            if random_x != self.owner.x and random_y != self.owner.y:
                self.owner.move_towards(random_x, random_y, game_map, entities)

            self.number_of_turns -= 1
        else:
            self.owner.ai = self.previous_ai
            results.append({'message': Message('The {0} is no longer confused!'.format(self.owner.name), libtcod.red)})

        return results
