<script>
export default {
    name: "SnackBar",
    data() {
        return {
            content: null
        }
    },
    computed: {
        hasContent() {
            return this.content !== null && this.content !== undefined && this.content.length > 0;
        }
    },
    methods: {
        setContent(content, timeout = 3000) {
            this.content = content;
            const that = this;

            setTimeout(function() {
                that.content = null;
            }, timeout);
        }
    }
}

export class SnackController {
    /**
     * The internal snack queue. Do not manipulate externally.
     * @type {Array<{c: String, t: Number}>}
     */
    static queue = [];

    /**
     * The Snackbar Vue component used by this controller.
     */
    static bar = null;

    /**
     * A value defining whether or not a snackbar is active. Do not manipulate externally.
     */
    static isActive = false;

    /**
     * Sets the Snackbar Vue component that this controller should use.
     */
    static setBar(snackBar) {
        this.bar = snackBar;
    }

    /**
     * Adds a snack to the queue.
     * @param {String} content The message of the snackbar.
     * @param {Number} timeoutMS The time in milliseconds for which the snack will be displayed.
     */
    static addSnack(content, timeoutMS = 3000) {
        this.queue.push({
            c: content,
            t: timeoutMS
        });

        if (!this.isActive) {
            this.eatSnacks();
        }
    }

    /**
     * Do not use this method externally.
     */
    static eatSnacks() {
        if (this.isActive || this.queue.length === 0) {
            return;
        }

        this.isActive = true;
        const { c, t } = this.queue.shift();
        this.bar.setContent(c, t);

        setTimeout(function() {
            SnackController.isActive = false;
            SnackController.eatSnacks();
        }, t + 500);
    }
}
</script>

<template>
<div class="paper bar" :class="{ 'bar-show': hasContent }">
    {{ content }}
</div>
</template>

<style lang="scss" scoped>
.bar {
    position: absolute;
    bottom: 1em;
    left: 35%;

    opacity: 0;
    width: 30%;

    transition-duration: 250ms;
    --paper-color: #2E2E2E;
    color: white;
}

.bar-show {
    opacity: 1;
}
</style>
