import _extends from 'babel-runtime/helpers/extends';
import Overlay from '../../overlay';
import { context } from './context';
import { mount } from '../../_utils/functional';
import { preventDefault } from '../../_utils/dom/event';

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

var overlay = void 0;

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

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

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

export function updateOverlay() {
    if (!overlay) {
        overlay = mount(Overlay, {
            on: {
                click: onClickOverlay
            }
        });
    }

    if (context.top()) {
        var _context$top2 = 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);
        }

        _extends(overlay, defaultConfig, config, {
            show: true
        });
    } else {
        overlay.show = false;
    }
}

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

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


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