import { cloneVNode, h } from "vue";
import { getComponent } from "../_util/props-util";
import { newInstace } from "../MessageManager";
import Icon from '../icon';
const iconMap = {
  success: h(Icon, {
    type: "check-circle"
  }),
  warning: h(Icon, {
    type: "warn-circle"
  }),
  error: h(Icon, {
    type: "close-circle"
  }),
  info: h(Icon, {
    type: "info-circle"
  }),
  loading: h(Icon, {
    type: "loading",
    spin: true
  })
};
let prefixCls = 'x-message';
let instance, promise;

async function getInstace() {
  if (promise) return promise;
  promise = newInstace({
    prefixCls
  });
  return instance = await promise;
}

let __key = 0;

function getKey() {
  return '__' + __key++;
}

const api = {
  add: options => {
    var _options$key;

    const key = (_options$key = options.key) !== null && _options$key !== void 0 ? _options$key : getKey();
    getInstace().then(inst => {
      inst.add({ ...options,
        key,
        content: () => [cloneVNode(options.icon || iconMap[options.type], {
          class: [`${prefixCls}_icon`, `${prefixCls}-${options.type}`]
        }), getComponent(options, 'content')]
      });
    });
    return () => {
      var _instance;

      return (_instance = instance) === null || _instance === void 0 ? void 0 : _instance.remove(key);
    };
  },
  destroyAll: () => instance.removeAll()
};
export const messageTypes = Object.keys(iconMap);
messageTypes.forEach(type => {
  api[type] = (content, options) => {
    return api.add({
      content,
      ...options,
      type
    });
  };
});

api.install = app => {
  app.config.globalProperties.$message = api;
};

export default api;