from core.system.grass import GrassSystem
from core.system.treasure import TreasureSystem
from core.terraform import conflict, foundation, biomes, underground, caves, way_crystals

from siege import game


class RealmGenerator(object):
    def __init__(self, world, realm):
        self.world = world
        self.realm = realm
        self.data = {
            'TreasureSystem': TreasureSystem,
            'GrassSystem': GrassSystem,
            'status': 'WorldGenLayFoundation',
            'minibiomes': [],
        }

    def start(self):
        self.actions = [
            (foundation.LayFoundation, "WorldGenLayFoundation"),
            (biomes.GenerateSurfaceBiomes, "WorldGenSurfaceBiomes"),
            (biomes.PlaceSurfaceBiomeStamps, "WorldGenPlaceSurfaceBiomes"),
            (biomes.QueueBiomeActions, ""),
            (foundation.PopulateStartArea, ""),
            (caves.PlaceCaves, "WorldGenPlaceCaves"),
            (underground.PlaceSediments, "WorldGenPlaceOres"),
            (underground.PlaceMetalOres, ""),
            (underground.PlaceUndergroundWater, "WorldGenPlaceWater"),
            (underground.PlaceUndergroundLava, ""),
            (underground.PlaceTreasureRooms, "WorldGenPopulateUnderground"),
            (underground.PlaceMushroomForests, ""),
            (underground.PlantMushroomTrees, ""),
            (underground.PlaceTreasureChests, ""),
            (underground.PlacePots, ""),
            (biomes.QueueBiomePostActions, "WorldGenFinishBiomes"),
            (way_crystals.PlaceSurfaceCrystals, "WorldGenPlaceCrystals"),
            (way_crystals.PlaceUndergroundCrystals, ""),
            (way_crystals.SpreadWayShards, ""),
            (conflict.Simulate, "WorldGenSimulateConflict"),
            (foundation.GrowGrass, "WorldGenSimulateGrass"),
            (foundation.SimulateWater, "WorldGenSimulateWater"),
            (foundation.Cleanup, "WorldGenCleanup"),
            (foundation.SaveWorldImage, ""),
        ]

        self.deferredActions = []

        self.actions.reverse()

    def resume(self):
        if self.actions:
            nextAction = self._getNextAction()
            deferredActions = nextAction(game, self.world, self.realm, self.data)
            if deferredActions:
                deferredActions.reverse()
                # New deferred actions are completed first.
                self.deferredActions = self.deferredActions + deferredActions
            return False
        else:
            return True

    def _getNextAction(self):
        if self.deferredActions:
            return self.deferredActions.pop()
        else:
            action, status = self.actions.pop()
            if status:
                self.data['status'] = status
            return action

    @property
    def status(self):
        return self.data['status']
