<script lang="ts">
    import { Hex } from "../hexgrid";
    import showBuildingCreator from "../stores/showBuildingCreator";
    import showBuildingPanel from "../stores/showBuildingPanel";
    import { getBuilding, getKeysAsNumbers } from "../utils";
    import village from "../village";
    import BuildingTile from "./BuildingTile.svelte";
    import Tile from "./Tile.svelte";


    function openBuildingCreator(tile: Hex) {
        showBuildingCreator.set(tile);
    }

    function openBuildingPanel(buildingId: number) {
        showBuildingPanel.set(buildingId);
    }
</script>

<section class="village-map">
    <div>
        { #each getKeysAsNumbers($village.villageTiles) as y }
        <div>
            { #each getKeysAsNumbers($village.villageTiles[y]) as x }
                { #if $village.villageTiles[y][x] >= 0 }
                    <Tile
                        onTileClick={ () => openBuildingPanel($village.villageTiles[y][x]) }
                    >
                        <BuildingTile building={ getBuilding($village, $village.villageTiles[y][x]) } />
                    </Tile>
                { :else }
                    <Tile
                        onTileClick={ () => openBuildingCreator(new Hex(x, y)) }
                    />
                { /if }
            { /each }
        </div>
        { /each }
    </div>
</section>

<style>
    .village-map {
        display: grid;
        height: 100%;
        position: relative;
    }

    .village-map > div {
        margin: auto;
    }
</style>
