<template>
    <section>
        <h3>
            <label class="uk-flex uk-flex-between uk-flex-middle">
                <span>
                    Stream (stream start, update and finish)
                </span>
                <span class="switch">
                    <input type="checkbox" v-model="enabled" @change="toggleStatus">
                    <span class="slider round"></span>
                </span>
            </label>
        </h3>
        <transition enter-active-class="animate__animated animate__slideInUp" leave-active-class="animate__animated animate__slideOutDown">
            <discord-webhook-message
                v-if="enabled"
                :data="JSON.parse($props.discordWebhookMessage)"
            ></discord-webhook-message>
        </transition>
    </section>
</template>
<script>
    import UIkit from "uikit";
    import { axios } from "../../app";

    export default {
        props: {
            active: {
                type: Boolean,
                value: false
            },
            subUnsubUrl: String,
            saveHookUrl: String,
            sendTestMessageUrl: String,
            discordWebhookMessage: String
        },
        data() {
            return {
                enabled: this.active,
            }
        },
        methods: {
            async toggleStatus() {
                let type = "stream";
                let mode = `${this.enabled ? "" : "un"}subscribe`;

                try {
                    let req = await axios.post(this.subUnsubUrl, {
                        type,
                        mode
                    });

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

                } catch (e) {
                    this.enabled = !this.enabled;
                    let errorMsg = `Error toggling the ${type} hook, retry after some seconds.`;

                    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.error(e);
                    }

                    UIkit.notification({
                        message: errorMsg,
                        status: "danger"
                    });
                }
            }
        }
    }
</script>
<style computed>
    /* mask the hook url unless editing or empty */
    input[type="url"]:not(:focus):not(:placeholder-shown) {
        filter: blur(4px);
    }
</style>