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

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

    let address = $derived(addr(code));
    let home = $derived(code.toLowerCase().includes('type=home'));
    let work = $derived(code.toLowerCase().includes('type=work'));

    function onSet(oldVal,newVal){
        const newCode = code.replace(oldVal,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('ADR','ADR;TYPE='+key));
    }

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

<div class="address">
    <div>
        <span class="symbol {home?'':'inactive'}" onclick={toggleHome}></span>
        <span class="symbol {work?'':'inactive'}" onclick={toggleWork} ></span>
    </div>
    <LineEditor wrapper="span" editable={true} value={address.box}       onSet={newVal => onSet(address.box,newVal)}       title={t('post_box')} />
    <LineEditor wrapper="span" editable={true} value={address.ext}       onSet={newVal => onSet(address.ext,newVal)}       title={t('extended_address')} />
    <LineEditor wrapper="span" editable={true} value={address.street}    onSet={newVal => onSet(address.street,newVal)}    title={t('street')} />
    <LineEditor wrapper="span" editable={true} value={address.post_code} onSet={newVal => onSet(address.post_code,newVal)} title={t('post_code')} />
    <LineEditor wrapper="span" editable={true} value={address.locality}  onSet={newVal => onSet(address.locality,newVal)}  title={t('locality')} />
    <LineEditor wrapper="span" editable={true} value={address.region}    onSet={newVal => onSet(address.region,newVal)}    title={t('region')} />
    <LineEditor wrapper="span" editable={true} value={address.country}   onSet={newVal => onSet(address.country,newVal)}   title={t('country')} />
</div>