from siege.util import minutes, TileRect
from core.helper import pixelRect
from core.terraform.helper import placeContentInArea, chunkDistribute


def PlaceSurfaceCrystals(game, world, realm, data):
    """ One way crystal in every other biome. """
    surfaceBiomes = [b for b in data['biomes'] if b.biome.layer == "surface"]
    startArea = TileRect(realm.startArea)
    startArea.resize(1, 1)
    for biome in surfaceBiomes[0::2]:
        if biome.area.intersects(startArea, realm.size.width):
            # PopulateStartArea step has already placed a way crystal here
            continue
        placeCrystal(game, realm, pixelRect(biome.area), onSurface=True)


def PlaceUndergroundCrystals(game, world, realm, data):
    DISTRIBUTION = 384

    def placementCallback(area):
        placeCrystal(game, realm, area, isUnderground=True)

    chunkDistribute(realm.size.tileWidth, data['undergroundArea'], DISTRIBUTION, placementCallback)


def SpreadWayShards(game, world, realm, data):
    for _ in xrange(50):
        game.travel.update(minutes(1))


def placeCrystal(game, realm, area, onSurface=False, isUnderground=False):
    contentEntity = game.content.get('way_crystal').entity
    crystal = placeContentInArea(realm, contentEntity, area, onSurface, isUnderground)
    game.travel.registerCrystal(crystal)
    return crystal
