import {
  createVNode,
  render,
} from 'vue'
import Dialog from './Dialog.vue'
import { MessageType } from '@idux/components/message/src/types'

class ToastInstance {
  public readonly show: (msg: string, type?: MessageType, autoClose?: boolean) => string
  public readonly close: (id: string) => void
  private readonly container: HTMLDivElement

  public constructor() {
    this.container = document.createElement('div')

    this.container.style.position = 'fixed'
    this.container.style.left = '50%'
    this.container.style.top = '1rem'
    this.container.style.zIndex = '999999999'

    let vm = createVNode(Dialog)

    render(vm, this.container)

    const app = document.getElementById('app')!

    app.append(this.container)

    this.show = (msg: string, type?: MessageType, autoClose?: boolean) => {
      return vm.component!.exposed!.showToast(msg, type, autoClose)
    }
    this.close = (id: string) => {
      vm.component!.exposed!.closeToast(id)
    }
  }

  public info(msg: string) {
    this.show(msg, 'info')
  }

  public success(msg: string) {
    this.show(msg, 'success')
  }

  public warning(msg: string) {
    this.show(msg, 'warning')
  }

  public error(msg: string) {
    this.show(msg, 'error')
  }

  public loading(msg: string, autoClose = false) {
    return this.show(msg, 'loading', autoClose)
  }
}

let instance: ToastInstance | null = null

export const useToast = () => {
  if (instance == null) {
    instance = new ToastInstance()
  }
  return instance
}

export default {
  show(msg: string, type?: MessageType, autoClose?: boolean) {
    useToast().show(msg, type, autoClose)
  },
  close(id: string) {
    useToast().close(id)
  },

  info(msg: string) {
    useToast().info(msg)
  },

  success(msg: string) {
    useToast().success(msg)
  },

  warning(msg: string) {
    useToast().warning(msg)
  },

  error(msg: string) {
    useToast().error(msg)
  },

  loading(msg: string, autoClose = false) {
    return useToast().loading(msg, autoClose)
  }
}
