import { useState, useEffect } from 'react';

const initialState = {
  recordingMinutes: 0,
  recordingSeconds: 0,
};

const MAX_RECORDER_TIME = 5;

const useTimerRecordAudio = (isRecording, callback) => {
  const [timerRecorder, setTimerRecorder] = useState(initialState);
  useEffect(() => {
    let recordingInterval = null;

    if (isRecording) {
      recordingInterval = setInterval(() => {
        setTimerRecorder(prevState => {
          if (
            prevState.recordingMinutes === MAX_RECORDER_TIME &&
            prevState.recordingSeconds === 0
          ) {
            callback();
            clearInterval(recordingInterval);
            return prevState;
          }

          if (
            prevState.recordingSeconds >= 0 &&
            prevState.recordingSeconds < 59
          ) {
            return {
              ...prevState,
              recordingSeconds: prevState.recordingSeconds + 1,
            };
          }

          if (prevState.recordingSeconds === 59) {
            return {
              ...prevState,
              recordingMinutes: prevState.recordingMinutes + 1,
              recordingSeconds: 0,
            };
          }
        });
      }, 1000);
    } else clearInterval(recordingInterval);

    return () => clearInterval(recordingInterval);
  }, [isRecording]);

  return timerRecorder;
};

export default useTimerRecordAudio;
