import { useEffect, useState } from "react";
import '../style/network-speed.less';
import { useBarStatus } from "../utils";
import { useMemoizedFn } from "ahooks";

const NetworkSpeed = ({ playObj, isLive }) => {

  const barStatus = useBarStatus(playObj);

  const [networkSpeed, setNetWordSpeed] = useState()

  const [chasingFramesFlag, setChasingFramesFlag] = useState(1)
  const flvStatisticsInfoChange = useMemoizedFn(e => {
    setNetWordSpeed(e?.speed || 0)
    let unplayedCache = playObj.getDuration() - playObj.getCurrentTime()
    if (unplayedCache > 5) {
      setChasingFramesFlag(2)

    } else if (unplayedCache > 3) {
      setChasingFramesFlag(1.5)

    } else if (unplayedCache > 1.5) {
      setChasingFramesFlag(1.2)

    } else if (unplayedCache > 0.8) {
      setChasingFramesFlag(1.1)
    } else {
      setChasingFramesFlag(1)
    }
  })

  useEffect(() => {
    if (!playObj?.__player || !isLive) {
      return
    }
    playObj.__player.playbackRate = chasingFramesFlag

  }, [chasingFramesFlag, playObj,isLive])

  useEffect(() => {
    const { flv, hls } = playObj || {}
    console.log(hls);



    try {
      // if (hls) {

      //   hls.on('onLevelLoaded', function (event, data) {
      //     var duration = data.details.duration;
      //     var bytesLoaded = data.stats.bytesLoaded;
      //     var bitrate = bytesLoaded / duration; // 计算码率
      //     console.log('Current bitrate:', bitrate, 'bytes/sec');
      //   })

      //   hls.on('onLevelLoading', function (event, data) {
      //     var bytesLoaded = data.stats.bytesLoaded;
      //     var bytesLoadedInSecond = bytesLoaded / 1000; // 转换为 Kbps
      //     console.log('Network speed:', bytesLoadedInSecond, 'Kbps');
      //   })
      // }
      if (flv?._emitter) {
        flv && flv.on('statistics_info', flvStatisticsInfoChange)
      }
    } catch (error) {
      console.error(error);

    }

    return () => {
      try {
        flv && flv._emitter && flv.off('statistics_info', flvStatisticsInfoChange)
      } catch (error) {

      }
    }
  }, [flvStatisticsInfoChange, playObj])
  return Number.isFinite(networkSpeed) && barStatus !== 'hide' ? <div className='lm-c-palyer-network-speed-view'>
    {`${(networkSpeed.toFixed(2) * 8)} Kbps`}
  </div> : null
}
export default NetworkSpeed