<template>
    <j-overlay v-model="isOpen"
               :body="true"
               :z-index="zIndex - 2"
               :opacity="0.8"
               bg="#000000">
    </j-overlay>
</template>

<script>
import { windowScrollbar } from 'libj-core';
var key = "__j-sidenav-body-bg";
window[key] = window[key] || document.body.style.backgroundColor;
export default {
    props: {
        value: {
            type: Boolean,
            default: null
        },
        navSelector: {
            type: String,
            default: '#mainMenu'
        },
        zIndex: {
            type: Number,
            default: 1031
        },
        direction: {
            default: 'ltr'
        }
    },
    data() {
        return {
            nav: null,
            isOpen: this.value
        };
    },
    mounted() {
        var init = () => {
            this.nav = $(this.navSelector);
            this.update();
        };
        $(init);
    },
    methods: {
        update() {
            this.isOpen = this.value;
            if (this.isOpen) {
                this.makeOpen();
            } else {
                this.makeClosed();
            }
        },
        makeOpen() {
            //show overlay
            window[key] = document.body.style.backgroundColor;
            document.body.style.backgroundColor = "rgba(0,0,0,0.4)";

            //disable scroll
            windowScrollbar.remove();

            //show
            var width = '250px';
            var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
            if (w > 350 && w <= 400) {
                width = '280px';
            } else if (w > 400 && w <= 700) {
                width = '280px';
            } else if (w > 700 && w <= 1100) {
                width = '320px';
            } else if (w > 1100) {
                width = '400px';
            }
            this.nav.css('width', width);
            this.nav.css('z-index', this.zIndex);
            this.nav.css(this.float, '0');
            this.nav.css(this.altFloat, 'auto');
            this.nav.children().show();
        },
        makeClosed() {
            //hide
            this.nav.children().hide();
            this.nav.css('width', '0px');

            //restore scroll
            windowScrollbar.restore();

            //remove overlay
            document.body.style.backgroundColor = window[key];
        }
    },
    computed: {
        float() {
            return this.direction === 'ltr' ? 'left' : 'right';
        },
        altFloat() {
            return this.direction === 'ltr' ? 'right' : 'left';
        }
    },
    watch: {
        value() {
            if (this.value === this.isOpen) {
                return;
            }
            this.update();
        }
    }
}
</script>