import { createVNode as _createVNode, mergeProps as _mergeProps } from "vue";
import { defineComponent, ref, createApp } from "vue"; // import { omit } from 'lodash-es'

import { omit } from "../_util/_";
import Message from "./Message";
let seed = 0;

function getUUID() {
  return '___' + seed++;
}

const MessageManager = defineComponent({
  name: 'message-manager',
  props: {
    prefixCls: String,
    max: Number
  },

  setup(props, {
    expose
  }) {
    const msgListRef = ref([]);
    const msgRefs = ref({});

    function add(options) {
      var _options$key;

      const key = (_options$key = options === null || options === void 0 ? void 0 : options.key) !== null && _options$key !== void 0 ? _options$key : getUUID();
      const msg = { ...options,
        key,
        close: () => remove(key)
      };
      const i = msgListRef.value.findIndex(msg => msg.key === key);

      if (~i) {
        // @ts-ignore
        msgListRef.value.splice(i, 1, msg);
      } else {
        if (msgListRef.value.length >= props.max) {
          msgListRef.value.shift();
        }

        msgListRef.value.push(msg);
      }

      return msg;
    }

    function remove(key) {
      msgRefs.value[key].close();
    }

    function removeAll() {
      msgListRef.value.forEach(msg => {
        remove(msg.key);
      });
    }

    function onAfterLeave(key) {
      msgListRef.value.splice(msgListRef.value.findIndex(msg => msg.key === key), 1);
      delete msgRefs[key];
    }

    expose({
      add,
      remove,
      removeAll
    });
    return () => {
      const {
        prefixCls
      } = props;
      const cls = `${prefixCls}-container`;
      return _createVNode("div", {
        "class": cls
      }, [msgListRef.value.map(msg => _createVNode(Message, _mergeProps(omit(msg, 'close'), {
        "prefixCls": prefixCls,
        "ref": inst => msgRefs.value[msg.key] = inst,
        "onAfterLeave": onAfterLeave.bind(null, msg.key)
      }), null))]);
    };
  }

});
export function newInstace(properties) {
  return new Promise(resolve => {
    const {
      getContainer,
      ...props
    } = properties;
    const div = document.createElement('div');
    const container = (getContainer === null || getContainer === void 0 ? void 0 : getContainer()) || document.body;
    container.appendChild(div);
    const instRef = ref();
    const app = createApp({
      mounted() {
        resolve(instRef.value);
      },

      render() {
        return _createVNode(MessageManager, _mergeProps(props, {
          "ref": instRef
        }), null);
      },

      unmounted() {}

    });
    app.mount(div);
  });
}
export default MessageManager;