import React from 'react'
import ReactDom from 'react-dom'
import IntelligentSearchPanel from './panel'
import { Config } from './types/IntelligentSearchPanel'
import { store } from './store'

export default class MesoorIntelligentSearch {
  injectedElement!: HTMLDivElement

  config!: Config

  constructor(injectedElement: HTMLDivElement, config: Config) {
    if (!injectedElement)
      throw new Error('MesoorIntelligentSearch: 缺少实例化参数injectedElement！')

    if (!config) throw new Error('MesoorIntelligentSearch: 缺少实例化参数config！')

    const { nodeType, nodeName } = injectedElement
    const { tenant, onSearch } = config

    if (nodeType !== 1 || nodeName !== 'DIV')
      throw new Error('MesoorIntelligentSearch: injectedElement 不是一个HTMLDIVElement！')

    if (typeof tenant !== 'string')
      throw new Error('MesoorIntelligentSearch: config.tenant应为string类型！')

    if (typeof onSearch !== 'function')
      throw new Error('MesoorIntelligentSearch: config.onSearch应为function类型！')

    Object.assign(this, {
      injectedElement,
      config,
    })
  }

  inject() {
    const { injectedElement, config } = this

    store.main.setConfig(config)

    ReactDom.render(<IntelligentSearchPanel />, injectedElement)
  }

  destory() {
    const { injectedElement } = this

    ReactDom.unmountComponentAtNode(injectedElement)
  }
}

export { IntelligentSearchPanel, store }
