<script lang="ts">
    import { onMount } from "svelte";
    import { inventory } from "../stores/inventory"
    import inventoryApi from "../stores/api";

    export let drinkName: string;

    let amountContainers: number;
    let amountBottles: number;

    const saveInventory = () => {
        // Check if a drink is already in the inventory. If yes, then update the amounts. If not, add it.
        if ($inventory.some(item => item.name === drinkName)) {
            // Potentially inefficient, how to refactor forEach?
            $inventory.forEach(item => {
                if (drinkName === item.name) {
                    item.amountContainers = amountContainers;
                    item.amountBottles = amountBottles;
                }
            });
        }
        else {
            $inventory = [
                {
                    name: drinkName,
                    amountContainers: amountContainers,
                    amountBottles: amountBottles,
                },
                ...$inventory,
            ];
        }
        inventoryApi.save($inventory);
    };

    const loadAmountsFromInventory = () => {
        $inventory.forEach(item => {
            if (item.name === drinkName) {
                amountContainers = item.amountContainers;
                amountBottles = item.amountBottles;
            }
        });
    }

    onMount(async () => {
        loadAmountsFromInventory();
    })

</script>

<div class="box">
    <div class="columns">
        <div class="column is-one-third">
            {drinkName}
        </div>
        <div class="column">
            <input class="input is-primary" type="number" placeholder="Anzahl volle Gebinde/Kästen" bind:value={amountContainers} on:input={saveInventory}>
        </div>
        <div class="column">
            <input class="input is-rounded" type="number" placeholder="Anzahl einzelne Flaschen" bind:value={amountBottles} on:input={saveInventory}>
        </div>
    </div>
</div>