<script>
    import { createEventDispatcher } from 'svelte';

    import Setting from './Setting.svelte';

    export let title;
    export let value;
    export let unit = '';
    export let min = null;
    export let max = null;
    export let decimal = false;

    const dispatch = createEventDispatcher();
    let error = null;
    function validate(event) {
        let v = event.target.value;

        if (v === '') {
            error = null;
            return;
        }

        let num = parseFloat(v);
        if (Number.isNaN(num)) {
            error = `"${v}" is not a number`;
        }
        else if (num % 1 !== 0 && !decimal) {
            error = `${num} is not a whole number`;
        }
        else if (min && num < min) {
            error = `Too low (minimum ${min})`;
        }
        else if (max && num > max) {
            error = `Too large (maximum ${max})`
        }
        else {
            error = null;
            value = num;
            dispatch('update', {value})
        }
    }
</script>


<Setting {title} {error}>
    <div slot="input">
        {#if unit}
            <span class="mr-2">{unit}:</span>
        {/if}
        <div class="tooltip tooltip-error" class:tooltip-open={error !== null} data-tip={error}>
            <input 
                type="text" 
                class="input input-sm input-bordered text-right max-w-[4rem]" 
                class:input-error={error} 
                value={value} 
                on:input="{validate}"
            />
        </div>
    </div>

    <slot name="description" slot="description"></slot>
</Setting>
