import React, { useState, useCallback, useEffect, useRef } from 'react';
import DateItem from './DateItem'

function Footer(props) {
  const { withTime = true, showDate } = props;
  const [date, setDate] = useState([]);
  const dateStrRef = useRef('');

  const timeBoxRef = useRef();

  const fixed0 = useCallback((num) => {
    num = parseInt(num)
    if (num < 10) num = "0" + num;
    return num + '';
  }, [])

  const getTime = useCallback(() => {
    let dateStr = dateStrRef.current;
    let currentDate = new Date();
    let year = currentDate.getUTCFullYear();
    year = fixed0(year);
    let month = currentDate.getMonth() + 1;
    month = fixed0(month);
    let day = currentDate.getDate();
    day = fixed0(day);
    let hour = currentDate.getHours();
    hour = fixed0(hour);
    let minute = currentDate.getMinutes();
    minute = fixed0(minute);
    let second = currentDate.getSeconds();
    second = fixed0(second);

    let newDate = `${year}-${month}-${day}`;
    let time = `${hour}:${minute}:${second}`;

    if (showDate) { 
      setDate(showDate.split(''));
    }else if(dateStr !== newDate && !showDate) {
      dateStrRef.current = newDate;
      setDate(newDate.split(''));
    }
    withTime && timeBoxRef.current && (timeBoxRef.current.innerText = time)
  }, [ withTime, showDate ]);

  const updateTime = useCallback(() => {
    getTime();
    if (!showDate) { 
      setTimeout(updateTime, 1000)
    }
  }, [getTime, showDate])

  useEffect(() => {
    updateTime();
    // eslint-disable-next-line
  }, [updateTime]);

  return (
    <div className="screen-footer">
      <div className="screen-footer-content">
        <span className="screen-footer-date">
          {date.map((item, index) => {
            return (
              <DateItem key={index} text={item} />
            )
          })}
        </span>
        <span className="screen-footer-time" ref={timeBoxRef}>
        </span>
      </div>
      <style jsx>{`
        .screen-footer{
          height: 82px;
          background: url('/img/footerBg.png') center bottom no-repeat;
          background-size: cover;
          position: absolute;
          width: 100%;
          bottom: 0;
          padding-top: 18px;
        }
        .screen-footer-content{
          color: white;
          font-weight: bold;
          width: 797px;
          height: 44px;
          line-height: 44px;
          text-align: center;
          margin: 0 auto;
        }
        .screen-footer-date{
          font-size: 36px;
          vertical-align: middle;
        }
        .screen-footer-time{
          font-size: 30px;
          font-family: 'Helvetica Neue';
          letter-spacing: 4px;
          vertical-align: middle;
          padding: 0 25px;
        }
      `}</style>
    </div>
  )
}

export default React.memo(Footer)