import PhotosActionTypes from "./photos.types";

const INITIAL_STATE = {
  photos: [],
  uploadInProgress: true,
  uploadError: null,
  jobid: null,
  progress: {},
  cancelTasks: {},
  cancelTriggered: false,
};

const photosReducer = (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case PhotosActionTypes.MEDIA_UPLOAD_START:
      return {
        ...state,
        photos: action.payload.photos,
        jobid: action.payload.jobid,
        uploadInProgress: true,
        uploadError: null,
        progress: action.payload.progress || {},
        cancelTasks: {},
        cancelTriggered: false,
      };
    case PhotosActionTypes.MEDIA_UPLOAD_FAILURE:
      return {
        ...state,
        uploadInProgress: false,
        uploadError: action.payload,
      };
    case PhotosActionTypes.MEDIA_UPLOAD_PROGRESS_UPDATE_ONE:
      return {
        ...state,
        progress: { ...state.progress, [action.payload.assetId]: { ...state.progress[action.payload.assetId], ...action.payload } }
      };
    case PhotosActionTypes.MEDIA_UPLOAD_SUCCESS_ONE:
      const { [action.payload.assetId]: _, ...remainingTasks } = state.cancelTasks;

      return {
        ...state,
        progress: { ...state.progress, [action.payload.assetId]: { ...state.progress[action.payload.assetId], progress: 1, status: 'completed', endTime: new Date() } },
        cancelTasks: remainingTasks
      };
    case PhotosActionTypes.MEDIA_UPLOAD_PROGRESS_UPDATE_BULK:
      return {
        ...state,
        progress: { Upload: { fileName: "Bulk", ...action.payload } }
      };
    case PhotosActionTypes.MEDIA_UPLOAD_COMPLETED:
      return {
        ...state,
        uploadInProgress: false,
        uploadError: null,
        photos: [],
        // progress: {},
        cancelTasks: {}
      };
    case PhotosActionTypes.CLEAR_UPLOAD_ERROR:
      return {
        ...state,
        photos: [],
        progress: {},
        uploadError: null,
        cancelTasks: {},
      };
    case PhotosActionTypes.ADD_UPLOAD_CANCEL_TASK:
      return {
        ...state,
        cancelTasks: {
          ...state.cancelTasks,
          [action.payload.assetId]: action.payload.cancelTask,
        },
      };
    case PhotosActionTypes.REMOVE_UPLOAD_CANCEL_TASK:
      const { [action.payload.assetId]: _2, ...remainingTasks2 } = state.cancelTasks; //2 added for scoped variable conflict.
      return {
        ...state,
        cancelTasks: remainingTasks2,
      };
    case PhotosActionTypes.CANCEL_UPLOADS:
      return {
        ...state,
        cancelTriggered: true,
      };
    case PhotosActionTypes.DELETE_MEDIA_SUCCESS: {
      return {
        ...state,
        progress: {}, //Clear it here so we only delete photos that were successful. 
      }
    }
    default:
      return state;
  }
};

export default photosReducer;
