<script lang="ts">
    import SerialConnection from "./SerialConnection.svelte";

    let port: SerialPort = null;

    async function connect() {
        port = await navigator.serial.requestPort();
        port.addEventListener("disconnect", disconnect);
    }

    async function disconnect() {
        port = null;
    }
</script>

<section class="section bg-footer">
    <div class="container">
        {#if navigator.serial}
            <div class="box parent">
                <span class="left">Serial available &#x1f680;</span>
                <span class="middle">
                    {#if port !== null}
                        <button class="button is-warning" on:click={disconnect}
                            >disconnect</button
                        >
                    {:else}
                        <button class="button is-primary" on:click={connect}
                            >connect</button
                        >
                    {/if}
                </span>
                <span class="right">
                    {#if port !== null}
                        <SerialConnection {port} />
                    {:else}
                        Not connected
                    {/if}
                </span>
            </div>
        {:else}
            <div class="notification is-danger text-center">
                <p>
                    Looks like your browser does not support WebSerial &#x1f622;
                </p>
                <p>
                    Check <a
                        href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Serial_API#browser_compatibility"
                        >here</a
                    > for a list of compatible browsers
                </p>
            </div>
        {/if}
    </div>
</section>

<style lang="scss">
    .parent {
        display: flex;
        flex-direction: row;
    }

    .left,
    .middle,
    .right {
        flex: 1;
    }

    .middle {
        text-align: center;
    }

    .right {
        text-align: right;
    }

    .text-center {
        text-align: center;
    }

    .bg-footer {
        background-color: hsl(0, 0%, 98%);
    }
</style>
