import { request } from 'utils/fetch';
import { actionTypes } from 'constants/action-types';
import { AnnState } from './announcement.types';
import { api } from 'constants/config';

export function getData() {
  return async (dispatch, getState) => {
    const { annData } = getState();
    if (!annData || !annData?.length) {
      let result = await request(api.notifications);
      let notices = localStorage.getItem('notices');
      if (notices) {
        notices = JSON.parse(notices);
        result = result && result.filter((e) => !notices?.includes(e.id));
      }
      dispatch({
        type: actionTypes.ANNOUNCEMENT_DATA,
        payload: result || []
      });
    }
  };
}

export function read() {
  return async (dispatch, getState) => {
    const { annData } = getState();
    let notices: any = localStorage.getItem('notices');
    notices = notices ? JSON.parse(notices) : [];
    annData.data && localStorage.setItem('notices', JSON.stringify([...annData.data.map((e) => e.id), ...notices]));
    dispatch({
      type: actionTypes.ANNOUNCEMENT_UPDATE,
      payload: []
    });
  };
}

type DATA = Array<AnnState>;

const initialState: { data: DATA } = {
  data: []
};

export default function reducer(state = initialState, { type, payload }): any {
  switch (type) {
    case actionTypes.ANNOUNCEMENT_DATA: {
      return { ...state, data: payload };
    }
    case actionTypes.ANNOUNCEMENT_UPDATE: {
      return { ...state, data: payload };
    }
    default:
      return state;
  }
}
