import random

from entity.entity import Entity
from entity.ghost import Ghost
from global_stuff import base


class Urn(Entity):
    model_name = 'urn'

    def __init__(self, tile, color, ghost_spawn_rate):
        super().__init__(tile, color)
        self.ghosts = set()
        self.ghost_spawn_rate = ghost_spawn_rate

    def start(self):
        base.task_mgr.do_method_later(
            1,
            self.spawn_ghost,
            'spawn_ghosts'+str(self.tile.x)+str(self.tile.y)
        )

    def __del__(self):
        if self.tile:
            base.task_mgr.remove('spawn_ghosts'+str(self.tile.x)+str(self.tile.y))
        for g in set(self.ghosts):
            g.__del__()
        super().__del__()

    def spawn_ghost(self, task):
        if self.ghost_spawn_rate <= 0:
            task.delay_time = 1
            return task.again
        task.delay_time = 1.0/self.ghost_spawn_rate

        if len(self.ghosts) >= 12 or any((g.tile == self.tile for g in self.ghosts)):
            return task.again

        self.ghosts.add(Ghost(self))
        return task.again