<script>
    import LineEditor from '../../Components/LineEditor.svelte';
    import { number } from '../../vcard.js';

    let { code, patch = (from, to) => true } = $props();

    let cell = $derived(code.toLowerCase().includes('type=cell'));
    let home = $derived(code.toLowerCase().includes('type=home'));
    let work = $derived(code.toLowerCase().includes('type=work'));
    let value = $derived(number(code));

    function onSet(newVal){
        const newCode = code.replace(value,newVal);
        return patch(code,newCode);
    }

    function toggleCell(){
        toggleType('CELL');
    }

    function toggleHome(){
        toggleType('HOME');
    }

    function toggleType(key){
        key = key.toUpperCase();
        if (code.toUpperCase().includes(';TYPE='+key)) {
            const regex = new RegExp(';TYPE='+key, "ig");
            patch(code,code.replace(regex,''));
        } else patch(code,code.replace('TEL','TEL;TYPE='+key));
    }

    function toggleWork(){
        toggleType('WORK');
    }
</script>

{#if value}
<span class="symbol {cell?'':'inactive'}" onclick={toggleCell} ></span>
<span class="symbol {home?'':'inactive'}" onclick={toggleHome}></span>
<span class="symbol {work?'':'inactive'}" onclick={toggleWork} ></span>
<LineEditor type="span" editable={true} {value} {onSet} /><br/>
{/if}