<template>
    <transition name="commonfade" mode="out-in">
        <div class="genModalBox" v-show="show">
            <div :class="modalClass">
                <div class="modalHeader"><h4><slot name="title">{{title}}</slot></h4><Icon :icon="['fabt', 'times']" class="icon close" v-show="!force" @click.stop="onClose(false)"/></div>
                <div class="modalContent"><slot></slot></div>
                <div class="modalFooter"><slot name="footer"></slot></div>
            </div>
        </div>
    </transition>
</template>

<script>
import { FontAwesomeIcon as Icon } from '@fortawesome/vue-fontawesome'
/**
* Generates modal dialogs for the application and is controlled via global event bus. Also supportes <b>Esc</b> key to close. Scrollable displays are not supported.
*/
export default {
	name: 'Modal',
	props: {
        /**
        * Type of modal display <i>small, medium, large</i>
        */
		type: {
			default: 'small',
			type: String
		},
        /**
        * Title of the modal box
        */
		title: {
			default: 'Sample title',
			type: String
		},
        /**
        * Forced modals cannot be closed using X button
        */
		force: {
			default: false,
			type: Boolean
		},
        /**
        * Unique identifier
        */
		id: {
			default: '',
			type: String
		},
        /**
        * Event declaration of component if the modal is loaded dynamically
        */
		baseEvent: {
			default: '',
			type: String
		}
	},
	components: {
		Icon
	},
	data() {
		return {
			show: false
		}
	},
	computed: {
		modalClass() {
			return 'genModal ' + this.type
		}
	},
	methods: {
		onClose(silent) {
			// This property should be the event name that is used on the base component where the modal forms and dynamically loaded
			if (this.baseEvent && !silent) {
				this.$events.emit(this.baseEvent, '')
			} else {
				this.show = false
			}
		},
		onShow() {
			this.show = true
		},
		listenKeys(e) {
			// Closes on Esc key press
			if (e.keyCode == 27 && !this.force) {
				this.onClose()
			}
		}
	},
	mounted() {
		this.$events.on(`closeModal|${this.id}`, this.onClose)
		this.$events.on(`showModal|${this.id}`, this.onShow)
		window.addEventListener('keyup', this.listenKeys, false)
	},
	beforeDestroy() {
		this.$events.off(`closeModal|${this.id}`)
		this.$events.off(`showModal|${this.id}`)
		window.removeEventListener('keyup', this.listenKeys, false)
	}
}
</script>
