import React, { useContext, useEffect, useState } from 'react'
import './index.less'
import Question from './Question'
import Demo from './Demo'
import CodeTest from './CodeTest'
import { SharedDataContext } from '../markdown'

type ActiveProps = {
  [key: string]: any
}

const Active: React.FC<ActiveProps> = (props) => {

  const { lang, value, position } = props

  const { reportData, getActivity, updateActivity, codePlayerConnect, execDemo, preActive } = useContext(SharedDataContext);


  // 活动id
  const [id, setId] = useState<string>()
  const [detail, setDetail] = useState({})

  // 解析出id,并进行初次的数据获取
  useEffect(() => {
    try {
      const _id = JSON.parse(value)?.id
      setId(_id)
      fetchDetail(_id)
    } catch (error) {

    }
  }, [value])

  // 监听变化 
  useEffect(() => {
    if (!id) return
    const updateValue = (event: any) => {
      if (event?.data?.type === 'updateActivity' && event?.data?.id === id) {
        // 重新获取当前数据
        fetchDetail(id)
      }
    }
    window.addEventListener("message", updateValue)
    return () => {
      window.removeEventListener("message", updateValue)
    }
  }, [id, ])

  // ----------------------------

  // 数据上报
  const report = () => {
    reportData?.({lang, id})
  }

  // 获取具体的数据
  const fetchDetail = async (id: string) => {
    const res = await getActivity(id)
    if (res) {
      setDetail(res)
    }
  }

  // shell执行
  const exec = () => {
    execDemo?.(detail)
  }

  return (
    <div className='active-md' data-start={position?.start?.line ?? ''} data-end={position?.end?.line ?? ''} data-page={props?.page ?? 0}>
      {
        lang === 'question' ? <Question data={detail} report={report} updateActivity={updateActivity} preActive={preActive}/> :
          lang === 'experiment' ? <Demo data={detail} report={report} exec={exec} preActive={preActive}/> :
            lang === 'validate' ? <CodeTest data={detail} report={report} codePlayerConnect={codePlayerConnect} updateActivity={updateActivity} preActive={preActive}/> : <></>
      }
    </div>
  )
}

export default Active