<script>
    import { activeField } from './field_sync.svelte.js';
    import { t }           from '../translations.svelte.js';

    let {
        editable = false,
        onclick  = evt => {},
        onSet    = newVal => {return true;},
        type     = 'div',
        value    = $bindable(null)
    } = $props();

    let editing   = $state(false);
    let editValue = $state(value);
    let timer     = null;
    let start     = 0;

    async function applyEdit(){
        let success = await onSet(editValue);
        if (success) value = editValue;
        editing = false;
    }

    function resetEdit(){
        editing   = false;
        editValue = value;
    }

    function startEdit(){
        activeField.update((n) => n+1);
        editing = editable;
    }

    function typed(ev){
        if (ev.keyCode == 13 && ev.ctrlKey) applyEdit();
        if (ev.keyCode == 27) resetEdit();
    }

    function measured(evt,duration){
        if (duration < 500){
            onclick(evt);
        } else {
            startEdit();
        }
    }

    function onmousedown(evt){
        evt.preventDefault();
        start = evt.timeStamp;
    }

    function onmouseup(evt){
        evt.preventDefault();
        measured(evt, evt.timeStamp - start);
    }

    function ontouchstart(evt){
        evt.preventDefault();
        start = evt.timeStamp;
    }

    function ontouchend(evt){
        evt.preventDefault();
        measured(evt, evt.timeStamp - start);
    }

    activeField.subscribe((val) => resetEdit());
</script>

<style>
    textarea{
        width: 100%;
        min-height: 100px;
    }
    div{
        min-width: 40px;
        min-height: 20px;
    }
    div.editable:hover{
        border: 1px dotted;
    }
</style>

{#if editable && editing}
<textarea bind:value={editValue} onkeyup={typed} autofocus></textarea>
{:else}
    {#if value}
    <svelte:element this={type} {onmousedown} {onmouseup} {ontouchstart} {ontouchend} class={{editable}} title={t('right_click_to_edit')} >
        {#each value.split("\n") as line}
        {line}<br/>
        {/each}
    </svelte:element>
    {/if}
{/if}