<script>
    import { invoke } from '@tauri-apps/api/core';
    import { createEventDispatcher } from 'svelte';
    import { fade } from 'svelte/transition';

    import ErrorAlert from '../../ui/ErrorAlert.svelte';


    export let local;
    export let isModified;

    const dispatch = createEventDispatcher();
    let alert;

    async function saveCredential() {
        await invoke('save_credential', {record: local});
        dispatch('save', local);
    }

    async function copyText(evt) {
        const tooltip = event.currentTarget;
        await navigator.clipboard.writeText(tooltip.dataset.copyText);
        const prevText = tooltip.dataset.tip;
        tooltip.dataset.tip = 'Copied!';
        window.setTimeout(() => tooltip.dataset.tip = prevText, 2000);
    }
</script>


<style>
    .grid {
        grid-template-columns: auto minmax(0, 1fr);
    }
</style>


<form class="space-y-4" on:submit|preventDefault={() => alert.run(saveCredential)}>
    <ErrorAlert bind:this={alert} />

    <div class="grid items-baseline gap-4">
        <span class="justify-self-end">Comment</span>
        <input
            type="text"
            class="input input-bordered bg-transparent"
            bind:value={local.credential.comment}
        >

        <span class="justify-self-end">Public key</span>
        <div
            class="tooltip tooltip-right"
            data-tip="Click to copy"
            data-copy-text={local.credential.public_key}
            on:click={copyText}
        >
            <div class="cursor-pointer text-left textarea textarea-bordered bg-transparent font-mono break-all">
                {local.credential.public_key}
            </div>
        </div>

        <span class="justify-self-end">Private key</span>
        <div
            class="tooltip tooltip-right"
            data-tip="Click to copy"
            data-copy-text={local.credential.private_key}
            on:click={copyText}
        >
            <div class="cursor-pointer text-left textarea textarea-bordered bg-transparent font-mono whitespace-pre overflow-x-auto">
                {local.credential.private_key}
            </div>
        </div>
    </div>

    <div class="flex justify-end">
        {#if isModified}
            <button
                transition:fade={{duration: 100}}
                type="submit"
                class="btn btn-primary"
            >
                Save
            </button>
        {/if}
    </div>
</form>