import createInstance from './instance.ts'

enum CMessageTypeEnum {
  text = 'text',
  success = 'success',
  error = 'error',
  warning = 'warning',
  info = 'info',
}

export type CMessageType = 'text' | 'success' | 'error' | 'warning' | 'info'

export interface CMessageOptions {
  type: CMessageType // 类型
  content: string // 消息内容
  icon?: string // 消息图标
  duration?: number // 自动关闭延迟时间
  close?: boolean // 是否显示关闭按钮
  to?: string | 'body' // 挂载位置 仅支持Id选择器 / body
}

function renderMsg(messageType: CMessageType, messageContent: string = '', options?: Partial<CMessageOptions>) {
  return new Promise((resolve) => {
    const defaultCfg: CMessageOptions = {
      type: 'text',
      content: '',
      icon: '',
      duration: 3000,
      close: false,
      to: 'body',
    }

    const config: CMessageOptions = Object.assign(
      { ...defaultCfg },
      { type: messageType, content: messageContent },
      { ...options },
    )

    const { type = 'text', content = '', icon = '', duration = 3000, close = false, to = 'body' } = config

    createInstance({
      type,
      content,
      duration,
      icon,
      close,
      to,
    })
    resolve('')
  })
}

export default {
  text(content = '', options?: Partial<CMessageOptions>) {
    return renderMsg(CMessageTypeEnum.text, content, options)
  },

  success(content = '', options?: Partial<CMessageOptions>) {
    return renderMsg(CMessageTypeEnum.success, content, options)
  },

  error(content = '', options?: Partial<CMessageOptions>) {
    return renderMsg(CMessageTypeEnum.error, content, options)
  },

  info(content = '', options?: Partial<CMessageOptions>) {
    return renderMsg(CMessageTypeEnum.info, content, options)
  },

  warning(content = '', options?: Partial<CMessageOptions>) {
    return renderMsg(CMessageTypeEnum.warning, content, options)
  },
}
