<template>
    <span ref="root"
          v-show="v">
        <slot></slot>
    </span>
</template>
<script>
import './jquery-equals';
import { guid, getOpacityCss } from "libj-core";
export default {
    props: {
        opacity: {
            type: Number,
            default: 0.25
        },
        zIndex: {
            type: Number,
            default: 1040
        },
        value: {
            type: Boolean,
            default: true
        },
        closeOnClick: {
            type: Boolean,
            default: false
        },
        body: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            id: guid.newId(),
            defaultStyle: "overflow: hidden;top:0;left:0;right:0;bottom:0;position:",
            styles: "",
            v: this.value,
            tag: null
        };
    },
    mounted() {
        $("body").on("click", "#" + this.id, this.p_onClick);
        this.$emit("init", {
            init: () => {
                this.p_updateStyles();
                this.p_checkVisibility();
            }
        });
    },
    methods: {
        p_onClick() {
            this.$emit("click");
            if (this.closeOnClick === true) {
                this.$emit("input", false);
            }
        },
        p_updateStyles() {
            var opacityCss = getOpacityCss(this.opacity);
            var s = `${this.defaultStyle}${this.p_getPosition()};`;
            this.styles = `z-index:${this.zIndex};${s};${opacityCss}`;
        },
        p_checkVisibility() {
            if (this.tag !== undefined && this.tag !== null) {
                this.tag.remove();
                this.tag = null;
            }
            if (this.v) {
                var parent = this.p_getParent();
                this.tag = $("<div></div>")
                    .attr("id", this.id)
                    .addClass('j-overlay')
                    .attr("style", this.styles)
                    .append(this.$el.outerHTML);
                parent.append(this.tag);
                this.$emit("input", true);
            } else {
                this.$emit("input", false);
            }
        },
        p_getParent() {
            if (this.body) {
                return $(document.body);
            }
            return $(this.$el).parent();
        },
        p_getPosition() {
            var parent = this.p_getParent();
            if (parent.equals($(document.body))) {
                return "fixed";
            }
            return "absolute";
        }
    },
    watch: {
        opacity(val, oldVal) {
            this.p_updateStyles();
        },
        zIndex(val, oldVal) {
            this.p_updateStyles();
        },
        value(val, oldVal) {
            this.v = this.value;
            this.p_updateStyles();
            this.p_checkVisibility();
        },
        body() {
            this.p_updateStyles();
            this.p_checkVisibility();
        }
    }
};
</script>