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

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

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

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

    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('EMAIL','EMAIL;TYPE='+key));
    }

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

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