import { Dispatch } from 'react';
import {
  CHANGE_SCALE,
  TOGGLE_DISPLAY_MODE,
  SET_SIDEBAR,
  SET_MARKUP_TOOL,
} from '../../constants/actionTypes';

const applyMiddleware = (state: any, dispatch: Dispatch<any>) => (action: {
  type: string;
  payload?: any;
}): void => {
  dispatch(action);
  switch (action.type) {
    case TOGGLE_DISPLAY_MODE: {
      if (action.payload === 'full') {
        const screenWidth = window.document.body.offsetWidth - 5;
        const originPdfWidth = state.viewport.width / state.scale;
        const rate = (screenWidth / originPdfWidth).toFixed(2);
        dispatch({ type: CHANGE_SCALE, payload: rate });
      } else {
        const screenWidth = window.document.body.offsetWidth - 288;
        const originPdfWidth = state.viewport.width / state.scale;
        const rate = screenWidth / originPdfWidth;
        dispatch({ type: CHANGE_SCALE, payload: rate });
      }
      break;
    }
    case SET_SIDEBAR: {
      if (action.payload === '') {
        dispatch({ type: SET_MARKUP_TOOL, payload: '' });
      }
      break;
    }
    default:
      break;
  }
};

export default applyMiddleware;
