import React, { useCallback, useEffect, useMemo, useRef } from 'react'
import Taro from '@tarojs/taro'

import { getConfig } from './config'
import posterSDKFactory from './sdk'

export default (canvasId, callback) => {

  const config = useMemo(() => getConfig(), [])
  const sdkRef = useRef()
  const cbRef = useRef()

  cbRef.current = callback

  const getPoster = useCallback((dataSource) => {
    const sdk = sdkRef.current
    if (!sdk) {
      return Promise.reject('系统未初始化完成, 请重试')
    }

    return new Promise((resolve, reject) => {
      const { poster, miniCode, name, avatar, desc = '长按识别在线看房',  } = dataSource || {}

      // 名称
      sdk.darwText(name, config.name)
      // 小程序码
      sdk.darwText(desc, config.desc)

      let cnt = 0
      // 封面
      sdk.getImage(poster).then((posterImg) => {
        sdk.drawImage(posterImg, config.poster)
        cnt += 1
      }).catch(() => cnt += 1)
      // 头像
      sdk.getImage(avatar).then((avatarImg) => {
        sdk.drawImage(avatarImg, config.avatar)
        cnt += 1
      }).catch(() => cnt += 1)
      // 小程序码
      sdk.getImage(miniCode).then((miniCodeImg) => {
        sdk.drawImage(miniCodeImg, config.miniCode)
        cnt += 1
      }).catch(() => cnt += 1)

      const ticker = setInterval(() => {
        if (cnt >= 3) {
          const image = sdk.toDataURL()
          clearInterval(ticker)
          resolve(image)
        }
      }, 200);
    })
  }, [config])

  useEffect(() => {
    Taro.nextTick(() => {
      posterSDKFactory(`#${canvasId}`).then((sdk) => {
        sdk.initCanvas({
          ...config,
        })
        sdkRef.current = sdk
        
        if (cbRef.current) {
          cbRef.current(getPoster)
        }
      })
    })
  }, [canvasId, config, getPoster])

  return;
}
