<script lang="ts">
    import moves from "../moves";
    import type { BuildingType, CostType, UnitType } from "../types";
    import { getUnitSource } from "../utils";
    import type { VillageState } from "../village";
    import village from "../village";
    import Cost from "./Cost.svelte";
    import RecruitmentQueue from "./RecruitmentQueue.svelte";

    export let building: BuildingType;


    let numberOfUnits = 1;
    $: unitType = building.behavior.units?.type || '';
    $: unit = getUnitSource(unitType);
    $: maximumUnits = getMaxCountOfUnits($village, unit);
    $: if (numberOfUnits > maximumUnits) {
        numberOfUnits = maximumUnits || 1;
    }
    $: cost = {
        wood: unit.cost.wood * numberOfUnits,
        stone: unit.cost.stone * numberOfUnits,
        iron: unit.cost.iron * numberOfUnits,
        food: unit.cost.food * numberOfUnits,
    };
    $: timeToRecruit = building.behavior.units?.recruitmentTime($village, building) * numberOfUnits;

    function recruit() {
        moves.recruitUnits(building.id, unitType, numberOfUnits);
    }

    function getMaxCountOfUnits(V: VillageState, unitData: UnitType): number {
        let res = Infinity;
        Object.entries(V.resources).forEach(([resource, value]) => {
            const cost = unitData.cost[resource as keyof CostType] || 0;
            if (cost > 0) {
                res = Math.min(
                    res,
                    Math.floor(value / cost)
                );
            }
        });

        return res;
    }

    function setMaxUnits() {
        numberOfUnits = maximumUnits;
    }
</script>

<div class="recruitment">
    <p>Recruit { unit.name }s</p>
    <div class="cost">
        <Cost { cost } duration={ timeToRecruit } />
    </div>

    <div>
        <input
            type="range"
            name="units"
            min="1"
            max={ maximumUnits }
            bind:value={ numberOfUnits }
        />
        <input
            type="number"
            name="units"
            min="1"
            max={ maximumUnits }
            bind:value={ numberOfUnits }
        />
        <button on:click={ setMaxUnits }>↑</button>
        <button on:click={ recruit } disabled={ numberOfUnits > maximumUnits }>Recruit</button>
    </div>
    <RecruitmentQueue { building } />
</div>

<style>
    .recruitment .cost {
        margin: 1em;
    }
</style>
