import '@lls/lls-ui/es/Loading/style.css'

import './style.less'

import classnames from 'classnames'
import * as React from 'react'
import ReactDOM from 'react-dom'

import Loading from '@lls/lls-ui/es/Loading'

import { getIsPadDisplay } from '../utils'

interface Props {
  force?: boolean
  isPad?: boolean
  text?: string
}

const LoadingComponent = (props: Props) => {
  const { force, isPad, text } = props
  return (
    <div
      className={classnames('ph-loading', {
        'is-pad': isPad,
        'info-loading': text
      })}
    >
      <div className="loading-wrapper">
        <Loading force={force} />
        {text && <p className="loading-text">{text}</p>}
      </div>
    </div>
  )
}

export default new class Loading {
  protected loadingEl: HTMLDivElement | null = null
  protected counter = 0

  public clear() {
    const { loadingEl } = this
    if (loadingEl) {
      this.loadingEl = null
      document.body.removeChild(loadingEl)
      this.counter = 0
    }
  }

  public show(text?: string, force?: boolean) {
    const isPad = getIsPadDisplay()
    if (this.counter <= 0) {
      this.loadingEl = this.addNode(
        <LoadingComponent isPad={isPad} force={force} text={text} />
      )
    }
    this.counter++
  }

  public hide() {
    const { loadingEl, counter } = this
    if (loadingEl && counter <= 1) {
      document.body.removeChild(loadingEl)
      this.loadingEl = null
    }
    if (counter > 0) this.counter--
  }

  protected addNode(element: JSX.Element) {
    const div = document.createElement('div')
    document.body.appendChild(div)
    ReactDOM.render(element, div)
    return div
  }
}()
