<script lang="ts">
    import {random_string} from "$shared/lib/helpers";
    import {afterUpdate, onMount} from "svelte";
    import {Temporal} from "@js-temporal/polyfill";

    const noCooldownSetting = "no-cooldown";
    // if no unique id is supplied, cooldown will not work between page loads. 
    // Therefore we are disabling it with noCooldownSetting in the fallback id.  
    export let id = "alert--" + noCooldownSetting + "--" + random_string(4);
    export let title = "";
    export let message = "";
    export let type = "info";
    export let closeable = false;
    export let closeableCooldown = "-1";
    export let visible = true;

    const cooldownStorageKey = "lastseen--" + id;
    $: cooldownEnabled = id.indexOf(noCooldownSetting) === -1 && closeable && (closeableCooldown === "~" || parseInt(closeableCooldown) > 0);

    function close() {
        visible = false;
        if (cooldownEnabled) {
            console.log("Cooldown enabled for " + id + ", " + closeableCooldown === "~" ? "with an endless cooldown" : "");
            localStorage.setItem(cooldownStorageKey, String(Temporal.Now.instant().epochSeconds));
        }
    }

    // Manages the state of the alert if cooldown is enabled
    function run_cooldown() {
        if (!cooldownEnabled) {
            console.log("Alert cooldown is not enabled for " + id);
            return;
        }
        if (!localStorage.getItem(cooldownStorageKey)) {
            console.log("Alert " + id + " has not been seen yet, displaying");
            visible = true;
            return;
        }
        if (!visible) {
            console.log("Alert " + id + " is not visible, stopping cooldown change")
            return;
        }
        if (closeableCooldown === "~") {
            console.log("Alert " + id + " has an infinite cooldown, hiding");
            visible = false;
            return;
        }

        const lastSeen = Temporal.Instant.fromEpochSeconds(localStorage.getItem(cooldownStorageKey) as number);
        if (Temporal.Instant.compare(Temporal.Now.instant(), lastSeen.add({seconds: parseInt(closeableCooldown)})) === 1) {
            console.log("Alert " + id + " has a cooldown of " + closeableCooldown + " and was last seen " + lastSeen.toLocaleString() + " making it due for a showing");
            visible = true;
        } else {
            visible = false;
        }
    }

    onMount(() => {
        if (cooldownEnabled) {
            run_cooldown();
        }
    })

    afterUpdate(() => {
        if (type === "default") {
            type = "primary";
        }
    });
</script>

<div class="alert alert--{type} padding-sm radius-md"
     id="{id}"
     class:alert--is-visible={visible}
     role="alert">
    <div class="flex justify-between">
        <div class="flex flex-row items-center">
            <svg class="icon icon--sm alert__icon margin-right-xxs"
                 viewBox="0 0 24 24"
                 aria-hidden="true">
                <path d="M12,0C5.383,0,0,5.383,0,12s5.383,12,12,12s12-5.383,12-12S18.617,0,12,0z M14.658,18.284 c-0.661,0.26-2.952,1.354-4.272,0.191c-0.394-0.346-0.59-0.785-0.59-1.318c0-0.998,0.328-1.868,0.919-3.957 c0.104-0.395,0.231-0.907,0.231-1.313c0-0.701-0.266-0.887-0.987-0.887c-0.352,0-0.742,0.125-1.095,0.257l0.195-0.799 c0.787-0.32,1.775-0.71,2.621-0.71c1.269,0,2.203,0.633,2.203,1.837c0,0.347-0.06,0.955-0.186,1.375l-0.73,2.582 c-0.151,0.522-0.424,1.673-0.001,2.014c0.416,0.337,1.401,0.158,1.887-0.071L14.658,18.284z M13.452,8c-0.828,0-1.5-0.672-1.5-1.5 s0.672-1.5,1.5-1.5s1.5,0.672,1.5,1.5S14.28,8,13.452,8z"></path>
            </svg>
            {#if title}
                <p class="text-sm">
                    <strong class="error-title">{title}</strong>
                </p>
            {:else if message}
                <div class="text-component text-sm break-word">
                    {@html message}
                </div>
            {/if}
        </div>
        {#if closeable}
            <button class="reset alert__close-btn"
                    on:click={close}>
                <svg class="icon"
                     viewBox="0 0 20 20"
                     fill="none"
                     stroke="currentColor"
                     stroke-linecap="round"
                     stroke-linejoin="round"
                     stroke-width="2">
                    <title>Close alert</title>
                    <line x1="3"
                          y1="3"
                          x2="17"
                          y2="17"/>
                    <line x1="17"
                          y1="3"
                          x2="3"
                          y2="17"/>
                </svg>
            </button>
        {/if}
    </div>

    {#if message && title}
        <div class="text-component text-sm break-word padding-top-xs">
            {@html message}
        </div>
    {/if}
</div>
