'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

exports.updateOverlay = updateOverlay;
exports.openOverlay = openOverlay;
exports.closeOverlay = closeOverlay;

var _overlay = require('../../overlay');

var _overlay2 = _interopRequireDefault(_overlay);

var _context = require('./context');

var _functional = require('../../_utils/functional');

var _event = require('../../_utils/dom/event');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var defaultConfig = {
    className: '',
    customStyle: {}
};

var overlay = void 0;

// close popup when click overlay && closeOnClickOverlay is true
function onClickOverlay(event) {
    (0, _event.preventDefault)(event, true);
    if (_context.context.top()) {
        var _context$top = _context.context.top(),
            vm = _context$top.vm;

        vm.$emit('click-overlay');

        if (vm.closeOnClickOverlay) {
            if (vm.onClickOverlay) {
                vm.onClickOverlay();
            } else {
                vm.close();
            }
        }
    }
}

function updateOverlay() {
    if (!overlay) {
        overlay = (0, _functional.mount)(_overlay2['default'], {
            on: {
                click: onClickOverlay
            }
        });
    }

    if (_context.context.top()) {
        var _context$top2 = _context.context.top(),
            vm = _context$top2.vm,
            config = _context$top2.config;

        var el = vm.$el;
        if (el && el.parentNode) {
            el.parentNode.insertBefore(overlay.$el, el);
        } else {
            document.body.appendChild(overlay.$el);
        }

        (0, _extends3['default'])(overlay, defaultConfig, config, {
            show: true
        });
    } else {
        overlay.show = false;
    }
}

function openOverlay(vm, config) {
    if (!_context.context.stack.some(function (item) {
        return item.vm === vm;
    })) {
        _context.context.stack.push({
            vm: vm,
            config: config
        });
        updateOverlay();
    }
}

function closeOverlay(vm) {
    var stack = _context.context.stack;


    if (stack.length) {
        if (_context.context.top().vm === vm) {
            stack.pop();
            updateOverlay();
        } else {
            _context.context.stack = stack.filter(function (item) {
                return item.vm !== vm;
            });
        }
    }
}