<template>
<transition name="commonfade" mode="out-in">
    <div class="genModalFormBox" v-show="show">
        <div :class="modalClass">
            <div class="modalFormHead">
                <h4><slot name="title">{{title}}</slot></h4>
                <Icon :icon="['fabt', 'times']" class="icon close" v-show="!force" @click.stop="onClose(false)"/>
                <a class="icon help" title="Help" :href="help" target="_blank" rel="noopener" v-if="help.length"><Icon :icon="['fabt', 'help']"/></a>
            </div>
            <div class="modalFormContent ignScrollUpdate" v-scrollbar="id"><slot></slot></div>
            <div class="modalFormFooter"><slot name="footer"></slot></div>
        </div>
    </div>
</transition>
</template>

<script>
import { FontAwesomeIcon as Icon } from '@fortawesome/vue-fontawesome'
import { URLREGEX } from '../../utils/constants'

export default {
	name: 'ModalForm',
	props: {
		// Unique identifier
		id: {
			default: '',
			type: String,
			required: true
		},
		// Title of modal box
		title: {
			default: 'Sample title',
			type: String
		},
		// Event declaration of component that has injected this dynamically
		baseEvent: {
			default: '',
			type: String
		},
		// Forced modals cannot be
		force: {
			default: false,
			type: Boolean
		},
		// Controls the size of modal box <i>full or medium</i>
		type: {
			default: 'full',
			type: String
		},
		// Links to websites where the guide for contents of this modal box is hosted
		help: {
			default: '',
			type: String,
			validate: value => {
				return URLREGEX.test(value)
			}
		}
	},
	components: {
		Icon
	},
	data() {
		return {
			show: true
		}
	},
	computed: {
		modalClass() {
			return 'modalFormWrapper ' + this.type
		}
	},
	methods: {
		onClose(silent) {
			// This property should be the event name that is used on the base component where the modal forms are dynamically loaded
			if (this.baseEvent && !silent) {
				this.$events.emit(this.baseEvent, '')
			} else {
				this.show = false
			}
		},
		listenKeys(e) {
			// Closes on Esc key press
			if (e.keyCode == 27 && !this.force) {
				this.onClose()
			}
		}
	},
	mounted() {
		this.$events.on(`closeModalForm|${this.id}`, this.onClose)
		window.addEventListener('keyup', this.listenKeys, false)
	},
	beforeDestroy() {
		this.$events.off(`closeModalForm|${this.id}`)
		window.removeEventListener('keyup', this.listenKeys, false)
	}
}
</script>
