<template>
    <v-dialog v-model="modal" :max-width="maxWidth" :width="width" :transition="transition">
        <slot :modal="modal" :data="data" v-if="modal"></slot>
    </v-dialog>
</template>

<script>
    import {mapGetters} from "vuex";

    export default {
        props: {
            width: {default: null},
            maxWidth: {default: null},
            name: {default: null},
            transition: {default: 'slide-x-transition'},
        },
        data: () => ({
            isOpenModal: false,
        }),
        computed: {
            ...mapGetters("modal", ["isModal", "getModal"]),
            modal: {
                get() {
                    const isOpen = this.isModal(this.modalName);
                    this.emitModal(isOpen);
                    return isOpen;
                },
                set(value) {
                    if (!value) {
                        this.$_closeModal();
                    }
                }
            },
            modalName() {
                return this.name ? this.name : this.$parent.$options.name;
            },
            data() {
                return this.getModal(this.modalName);
            }
        },
        methods: {
            emitModal(isOpen) {
                if (this.isOpenModal && !isOpen) {
                    this.isOpenModal = false;
                    this.$emit('close');
                } else if (!this.isOpenModal && isOpen) {
                    this.isOpenModal = true;
                    this.$emit('open', this.data);
                    this.$parent.modalData = this.data;
                }
            }
        },
        beforeDestroy() {
            this.emitModal(false);
        }
    }
</script>
