@extends("layouts.app")

@section("title", "Dashboard")

@section("content")

<div class="uk-container">
    <h3 class="uk-text-center">Dashboard</h3>

    <h2>Available events</h2>

    <section>
        <h3>
            <label class="uk-flex uk-flex-between">
                <span>
                    Stream (stream start, update and finish)
                </span>
                <span class="switch">
                    <input type="checkbox" id="stream-hook" {{ ($streamHook && !($streamHook->disabled || $streamHook->disabled_at)) ? "checked" : "" }}>
                    <span class="slider round"></span>
                </span>
            </label>
        </h3>
        <div>
            <p>
                <span uk-icon="info"></span> A message will be sent to the channel when a stream is started.
            </p>
            <div role="form" class="uk-flex" id="discord-webhook">
                <input type="url" class="uk-input" name="discord_hook_url" placeholder="Discord webhook URL" value="{{ ($streamHook && $streamHook->webhookActions()->first()) ? $streamHook->webhookActions()->first()->discord_hook_url : "" }}" {{ (!$streamHook || ($streamHook->disabled || $streamHook->disabled_at)) ? "disabled" : "" }} />
                <button name="save" class="uk-button uk-button-primary uk-hidden" uk-icon="check" style="flex-shrink: 0;"></button>
                <button name="test" class="uk-button uk-button-default" style="flex-shrink: 0;">Send test message</button>
            </div>
        </div>
    </section>

    <style>
    /* mask the hook url unless editing or empty */
    #discord-webhook input[type="url"]:not(:focus):not(:placeholder-shown) {
        filter: blur(4px);
    }
    </style>

    <script>
    let streamHook = document.getElementById("stream-hook");

    let hookActionForm = document.getElementById("discord-webhook");
    let discordWebhookUrl = hookActionForm.querySelector("[name=discord_hook_url]");
    let discordWebhookSaveBtn = hookActionForm.querySelector("[name=save]");
    let discordWebhookTestBtn = hookActionForm.querySelector("[name=test]");

    let INIT_DISCORD_HOOK_URL = discordWebhookUrl.value;

    // subscribe unsubscribe from stream hook events
    streamHook.addEventListener("change", async function() {
        let type = "stream";
        let mode = `${this.checked ? "" : "un"}subscribe`;

        discordWebhookUrl.disabled = !discordWebhookUrl.disabled;

        try {

            let req = await axios.post("{{ route("hooks.twitch.subscribe") }}", {
                type: type,
                mode: mode
            });

            UIkit.notification({
                message: `Saved!`,
                status: "success"
            });

        } catch (e) {

            this.checked = !this.checked;
            discordWebhookUrl.disabled = !discordWebhookUrl.disabled;

            let errorMsg = `Error toggling the ${type} hook, retry after some seconds.`;

            // validation error
            switch(e.request.status) {
                case 422:
                errorMsg = e.response.data.message;
                break;
                case 503:
                errorMsg = "Site is in maintenance, retry in some minutes...";
                break;
                default:
                console.log(e);
            }

            UIkit.notification({
                message: errorMsg,
                status: "danger"
            });

        }
    });

    // toggle the visibility of the save button
    discordWebhookUrl.addEventListener("keyup", function () {
        let show = false;

        if (this.value.trim().length >= "https://discordapp.com/api/webhooks/".length) {

            if (this.value !== INIT_DISCORD_HOOK_URL) {
                show = true;
            }
        }

        if (
            (show && discordWebhookSaveBtn.classList.contains("uk-hidden"))
            ||
            (!show && !discordWebhookSaveBtn.classList.contains("uk-hidden"))
        ) {
            discordWebhookSaveBtn.classList.toggle("uk-hidden");
        }
    });

    // save discord webhook url
    discordWebhookSaveBtn.addEventListener("click", async function () {
        // disable editing the url and hide save button
        discordWebhookUrl.toggleAttribute("disabled");
        this.classList.toggle("uk-hidden");

        try {

            let req = await axios.post("{{ route("hooks.twitch.action.add") }}", {
                type: "stream",
                discord_hook_url: discordWebhookUrl.value
            });

            UIkit.notification({
                message: `Updated!`,
                status: "success"
            });

            INIT_DISCORD_HOOK_URL = discordWebhookUrl.value;

        } catch (e) {
            let errorMsg = "The new url could not be saved, try again after some seconds.";

            // validation error
            switch(e.request.status) {
                case 422:
                    errorMsg = e.response.data.errors[discordWebhookUrl.name];
                    break;
                case 503:
                    errorMsg = "Site is in maintenance, retry in some minutes...";
                    break;
                default:
                    console.log(e);
            }

            UIkit.notification({
                message: errorMsg,
                status: "danger"
            });

            this.classList.toggle("uk-hidden");

        }

        // make editable the webhook url
        discordWebhookUrl.toggleAttribute("disabled");
    });

    // send test message
    discordWebhookTestBtn.addEventListener("click", async function () {
        try {
            let req = await axios.post("{{ route("hooks.twitch.action.test.discord") }}", {
                discord_hook_url: discordWebhookUrl.value
            });

            UIkit.notification({
                message: `Test message sent`,
                status: "success"
            });

        } catch (e) {

            let errorMsg = "There was an error sending the test message.";

            // validation error
            switch(e.request.status) {
                case 422:
                    errorMsg = e.response.data.errors[discordWebhookUrl.name];
                    break;
                case 503:
                    errorMsg = "Site is in maintenance, retry in some minutes...";
                    break;
                default:
                    console.log(e);
            }

            UIkit.notification({
                message: errorMsg,
                status: "danger"
            });

        }
    });
    </script>

</div>

@endsection
