import React, {Fragment, useState, useRef, useEffect} from 'react'
import Flipper from './Flipper'
import './flipper.css'

const FlipView = ({number = '0'}) => {

  const [lastArray, setLastArray] = useState(['0', '0', '0', '0', '0', '0']);
  const flipper0 = useRef();
  const flipper1 = useRef();
  const flipper2 = useRef();
  const flipper3 = useRef();
  const flipper4 = useRef();
  const flipper5 = useRef();
  const flipper6 = useRef();

  useEffect(() => {
    run();
  }, [number]);

  ///////////////////////////////////////// 逻辑方法

  /**
   * 开始翻牌
   */
  const run = () => {
    let tempArray = new Array(6 - number.length);
    let array = tempArray.concat([...number.split('')]);

    const flipDown = (front, back, ref) => {
      front = front || "0";
      back = back || "0";
      if (front != back) {
        ref && ref.current.flipDown(back, front);
      }
    };

    flipDown(array[0], lastArray[0], flipper1);
    flipDown(array[1], lastArray[1], flipper2);
    flipDown(array[2], lastArray[2], flipper3);
    flipDown(array[3], lastArray[3], flipper4);
    flipDown(array[4], lastArray[4], flipper5);
    flipDown(array[5], lastArray[5], flipper6);

    setLastArray(array);

  };

  ///////////////////////////////////////// 页面渲染

  return <Fragment>
    <Flipper ref={flipper0}/>
    <em style={{fontSize: 36, margin: '0 5px'}}>,</em>
    <Flipper ref={flipper1}/>
    <Flipper ref={flipper2}/>
    <Flipper ref={flipper3}/>
    <em style={{fontSize: 36, margin: '0 5px'}}>,</em>
    <Flipper ref={flipper4}/>
    <Flipper ref={flipper5}/>
    <Flipper ref={flipper6}/>
  </Fragment>

};


export default FlipView;
