import React, {createContext, useReducer} from 'react';

const PlayerStateContext = createContext();
const PlayerDispatchContext = createContext();

const initialPlayerState = {
    volume: 1,
    muted: false,
    duration: 0.0,
    currentTime: 0.0,
    currentPosition: 0.0,
    paused: true,
    uri: 'https://sample-videos.com/audio/mp3/crowd-cheering.mp3',
    player: null
};

const playerReducer = (state, action) => {
    switch(action.type) {
      case 'muted':
        return {
          ...state,
          muted: !state.muted
        };
      case 'paused':
        return {
          ...state,
          paused: action.setPaused
        };
      case 'uri':
        return {
          ...state,
          uri: action.setUri
        };
      case 'duration':
        return {
          ...state,
          duration: action.setDuraton
        };
      case 'currentTime':
        return {
          ...state,
          currentTime: action.setCurrentTime
        };
      case 'currentPosition':
        return {
          ...state,
          currentPosition: action.setCurrentPosition
        };
      case 'player':
        return {
          ...state,
          player: action.player
        };
      case 'seek':
        state.player && state.player.current.seek(action.seekValue);
        return state;
      case 'stop':
        state.player && state.player.current.seek(0);
        return state;            
      default: throw new Error('Action type is not match');  
    }
};

const PlayerConextProvider = ({children}) => {
  const [playerState, playerDispatch] = useReducer(playerReducer, initialPlayerState);
  return (
    <PlayerDispatchContext.Provider value={playerDispatch}>
      <PlayerStateContext.Provider value={playerState}>
        {children}
      </PlayerStateContext.Provider>
    </PlayerDispatchContext.Provider>

  );
}

/**
 *  Player Common Function
 */

const secondsTohhmmss = (seconds, timeFormat='hmmss') => {
  const format = val => `0${Math.floor(val)}`.slice(-2);
  const hours = seconds / 3600;
  const minutes = (seconds % 3600) / 60;

  if(timeFormat==='mmss' || ~~hours===0) {
    return [minutes, seconds % 60].map(format).join(':');
  }
  if(timeFormat==='hmmss') {
    return `${~~hours}:${[minutes, seconds % 60].map(format).join(':')}`;
  }
  if(timeFormat==='hhmmss') {
    return [hours, minutes, seconds % 60].map(format).join(':');
  }
}

const playerCommon = {
  secondsTohhmmss: secondsTohhmmss
};

export { PlayerDispatchContext, PlayerStateContext, PlayerConextProvider, playerCommon }