<template>
    <div class="toastContainer" @click.stop="linkListener" :data-id="id">
        <Message v-for="(m, idx) in list" :key="idx" :type="m.type" :message="m.message" :title="m.title" :important="m.important"/>
    </div>
</template>

<script>
import { isString } from 'lodash'
import Message from './Messaging'
export default {
    name: 'Messages',
    props: {
        id: {
            type: String,
            required: true
        }
    },
    components: {
        Message
    },
    data () {
        return {
            list: []
        }
    },
    methods: {
        linkListener (e) {
            e.preventDefault()
            if (isString(e.target.className) && e.target.className.contains('msgLink')) {
                this.$events.emit(e.target.getAttribute('data-attr'))
            }
        },
        listenKeys (e) {
            // Close all messages with Alt+X combination
            if (e.altKey) {
                if (e.keyCode == 88) {
                    this.list = []
                }
            }
        }
    },
    mounted () {
        this.$events.on('showMessage', (data) => {
            if (this.id == data.id) {
                if (this.list.length > 10) {
                    this.list = []
                }
                this.list.push(data)
            }
        })
        this.$events.on('clearMessage', (data) => {
            if (this.id == data.id) {
                this.list = []
            }
        })
        window.addEventListener('keydown', this.listenKeys, false)
    },
    beforeDestroy () {
        this.$events.off('showMessage')
        this.$events.off('clearMessage')
        window.removeEventListener('keydown', this.listenKeys)
    }
}
</script>
