<template>
    <transition :name="transition">
        <div :id="id"
             :style="styles"
             class="modal-raw"
             ref="div"
             v-show="isVisible">
            <j-overlay :opacity="overlayOpacity"
                       :z-index="overlayZIndex"
                       v-model="isOverlayVisible"
                       :close-on-click="closeOnClick"
                       :body="true"
                       @click="p_overlayClick"></j-overlay>
            <slot></slot>
        </div>
    </transition>
</template>
<script>
import { guid, queryMedia, windowScrollbar } from "libj-core";
import { findLastIndex } from "./util";
const initialZIndex = 1050;
var key = "__j-modals";
var containerKey = "__j-modals-container";
var first = false;
if (window[key] === undefined || window[key] === null) {
    window[key] = [];
    window[containerKey] = guid.newId();
    first = true;
}
function modalCollection() {
    var list = window[key];
    this.add = modal => {

        //correct z-index
        var lastModal = list.length > 0 ? list[list.length - 1] : null;
        var lastZIndex = lastModal === undefined || lastModal === null ? initialZIndex : lastModal.zIndex;
        modal.setZIndex(lastZIndex + 1);

        list.push(modal);
        if (list.length === 1) {
            windowScrollbar.remove();
        }
    };
    this.remove = modal => {
        var i = list.findIndex(a => {
            return a === modal;
        });
        if (i > -1) {
            list.splice(i, 1);
        } else {
            console.log(modal);
        }
        if (list.length === 0) {
            windowScrollbar.restore();
        }
    };
    this.hideLastOnEscape = () => {
        var i = findLastIndex(list, a => {
            return a.closeOnEscape;
        });
        if (i > -1) {
            list[i].$emit("input", false);
        }
    };
    this.insertModal = modal => {
        $("#" + window[containerKey]).prepend(modal.$el);
    };
    this.getLastModal = () => {
        return list.length > 0 ? list[list.length - 1] : null;
    };
}
var modals = new modalCollection();
if (first) {
    $(document.body).append($("<span></span>").attr("id", window[containerKey]));
    $(document).keyup(e => {
        var code = e.keyCode || e.which;
        if (code === 27) {
            modals.hideLastOnEscape();
        }
    });
}
export default {
    props: {
        value: {
            type: Boolean,
            default: false
        },
        overlay: {
            type: Boolean,
            default: true
        },
        overlayOpacity: {
            type: Number,
            default: 0.4
        },
        borderCss: {
            type: String,
            default: "1px solid dodgerblue"
        },
        margin: {
            type: String,
            default: "10%" //e.g: 10px, 5%
        },
        closeOnClick: {
            type: Boolean,
            default: true
        },
        closeOnEscape: {
            type: Boolean,
            default: true
        },
        // fade, bounce
        transition: {
            type: String,
            default: "fade"
        },
        maxHeight: {
            default: null
        }
    },
    data() {
        return {
            id: guid.newId(),
            isVisible: false,
            overlayZIndex: 1040,
            isOverlayVisible: false,
            isMobile: false,
            zIndex: initialZIndex
        };
    },
    mounted() {
        modals.insertModal(this);
        queryMedia.run("(max-width: 600px)", true, isMobile => {
            this.isMobile = isMobile;
            this.p_update();
        });
        this.p_update();
    },
    computed: {
        styles() {
            var m = this.isMobile ? '0px' : this.margin;
            return {
                overflow: 'hidden',
                position: 'fixed',
                transition: 'opacity .4s ease',
                top: m,
                left: m,
                right: m,
                bottom: m,
                border: this.borderCss,
                'z-index': this.zIndex,
                'max-height': this.maxHeight
            };
        }
    },
    methods: {
        p_overlayClick() {
            if (this.closeOnClick) {
                this.$emit("input", false);
            }
        },
        setZIndex(zIndex) {
            this.zIndex = zIndex;
        },
        p_update() {
            var zIndex = parseInt($(this.$refs.div).css("z-index"));
            this.overlayZIndex = isNaN(zIndex) ? initialZIndex : zIndex - 1;
            if (this.value) {
                this.p_show();
            } else {
                this.p_hide();
            }
        },
        p_show() {
            if (this.isVisible) {
                return;
            }
            var args = { cancel: false };
            this.$emit("showing", args);
            if (args.cancel === true) {
                return;
            }
            modals.add(this);
            this.isVisible = true;
            this.isOverlayVisible = this.isVisible && this.overlay;
            this.$emit("show");
        },
        p_hide() {
            if (!this.isVisible) {
                return;
            }
            var args = { cancel: false };
            this.$emit("hiding", args);
            if (args.cancel === true) {
                return;
            }
            modals.remove(this);
            this.isVisible = false;
            this.isOverlayVisible = false;
            this.$emit("hide");
        }
    },
    watch: {
        margin() {
            this.p_update();
        },
        borderCss() {
            this.p_update();
        },
        overlay() {
            this.p_update();
        },
        value() {
            this.p_update();
        },
    }
};
</script>