import React, { useMemo,useState,useCallback ,useRef} from 'react';
import Player from '../Base';
import { getLoopBoxSize } from '../utils';
import '../style/loop.less';

function LoopVideo({ screenNum, loopBoxs, className,cursorPosition, playList, style, containerRef, isLoop, onCloseVideo, switchHistoryVideo, switchLiveVideo, downloadVideo, onFrontEndSeek, addPreset, openPresetPanel, presetCid  }) {
  const screens = useMemo(() => new Array(screenNum).fill(true).map((_, index) => index), [screenNum]);
  const size = useMemo(() => getLoopBoxSize(screens.length), [screens]);
  const inputRef =  useRef();
  const [indexScreen,setIndex] = useState(-1);
  const selectScreen = useCallback((index)=>{
    let cursorIndex = -1;
    if(indexScreen !== index){
      cursorIndex = index;
    }
    cursorPosition && cursorPosition(cursorIndex);
    setIndex(cursorIndex);
  },[indexScreen,cursorPosition]);

  return (
    <div className={`loop-video-layout ${className}`} style={style} ref={containerRef}>
      {screens.map((_, index) => (
        <div style={{ width: size, height: size, padding: 1 }} className={indexScreen === index && cursorPosition ? "selectScreen" : ""} onClick = {() => {cursorPosition && selectScreen(index)}} key={index}>
          <Player
            {...playList[index]}
            onClose={() => onCloseVideo(index)}
            isLoop={isLoop ? loopBoxs[index] : false}
            switchHistoryVideo={args => switchHistoryVideo({ ...args, index })}
            switchLiveVideo={args => switchLiveVideo({ ...args, index })}
            downloadVideo={args => downloadVideo({ ...args, index })}
            onFrontEndSeek={args => onFrontEndSeek({ ...args, index })}
            openPresetPanel={openPresetPanel}
            addPreset={addPreset}
            screenNum={screenNum}
            presetCid={presetCid}
            inputRef={inputRef}
          />
        </div>
      ))}
    </div>
  );
}

LoopVideo.defaultProps = {
  screenNum: 4,
  playList: [],
  className: '',
  loopBoxs: []
};

export default React.memo(LoopVideo);
