import { types } from "../actions/actionTypes";

const initialState = {
  subTitleBlobs: {},
  chatData: null,
};

export const playReducer = (state = initialState, action) => {
  switch (action.type) {
    case types.GET_CHAT_LOG:
      return {
        ...state,
        chatData: action.payload.text,
      };
    case types.GET_SUBTITLE: {
      let srtText = action.payload.data?.text;
      if (!srtText) {
        return {
          ...state,
          subTitleBlobs: {
            ...state.subTitleBlobs,
            [action.payload.url]: "Error",
          },
        };
      }
      var srtRegex =
        /(.*\n)?(\d\d:\d\d:\d\d),(\d\d\d --> \d\d:\d\d:\d\d),(\d\d\d)/g;
      var vttText = "WEBVTT\n\n" + srtText.replace(srtRegex, "$1$2.$3.$4");
      var vttBlob = new Blob([vttText], { type: "text/vtt" });
      let blobUrl = URL.createObjectURL(vttBlob);

      return {
        ...state,
        subTitleBlobs: {
          ...state.subTitleBlobs,
          [action.payload.url]: blobUrl,
        },
      };
    }
    case types.CLEAR_PLAYER_INFO: {
      return {
        ...state,
        chatData: {},
      };
    }

    default:
      return state;
  }
};
