from collections import defaultdict

from core.component.spawner import SpawnerComponent
from siege import game
from siege.subsystem import Subsystem


class SpawnerSystem(Subsystem):
    NAME = "spawner"

    def getName(self):
        return self.NAME

    def __init__(self):
        Subsystem.__init__(self)
        self.biomeSpawners = defaultdict(list)
        self.spawners = []
        self.enabled = True
        self.freeze()

    def create(self, entity, type, definition):
        component = SpawnerComponent(definition)
        entity.add(component)
        self.add(entity)

    def add(self, entity):
        if entity.has(SpawnerComponent.CID):
            spawner = entity.spawner
            if entity.isContentEntity():
                for biome in spawner.biomes:
                    self.biomeSpawners[biome].append(entity)
            else:
                self.spawners.append((entity, spawner))

    def remove(self, entity):
        pass

    def getCount(self):
        return len(self.spawners)

    def clear(self, entity):
        del self.spawners[:]
        self.biomeSpawners.clear()

    def update(self, frameTime):
        for entity, spawner in self.spawners:
            spawner.update(frameTime)

    def getSpawnersForBiome(self, biomeName):
        return self.biomeSpawners[biomeName]

    @staticmethod
    def register():
        spawnerSystem = SpawnerSystem()
        game.registerSubsystem(spawnerSystem, SpawnerSystem.NAME, SpawnerComponent.TYPE)
