import { actionTypes } from 'constants/action-types';
import { Dispatch } from 'redux';
import { ScreensStatusState, ScreenStatusCode } from './screenStatus.types';

/**
 * 存在statusCode则派发action
 * @param dispatch
 * @param payload
 */
export const dispatchUpdateScreenStatus = (
  dispatch: Dispatch<{
    type: string;
    payload: { screenId: number; statusCode?: ScreenStatusCode };
  }>,
  payload: { screenId: number; statusCode?: ScreenStatusCode },
) => {
  const { screenId, statusCode } = payload;
  if (!statusCode) return;
  dispatch({
    type: actionTypes.UPDATE_SCREEN_STATUS,
    payload: {
      screenId,
      statusCode: typeof statusCode === 'number' ? statusCode : 200,
    },
  });
};

const screensStatus = (
  state: ScreensStatusState = {},
  { type, payload }: { type: string; payload: { screenId: number; statusCode?: ScreenStatusCode } },
) => {
  if (actionTypes.UPDATE_SCREEN_STATUS === type && payload.statusCode) {
    const { screenId, statusCode } = payload;
    return { ...state, [screenId]: statusCode };
  }
  return state;
};
export default screensStatus;
