import { actionTypes } from 'constants/action-types';
import http from 'utils/fetch';
import { api } from 'constants/config';
import { addFontsByStyle } from 'utils/font';
import { Dispatch } from 'redux';
import { FontInfoFromServer } from './font.types';
import { getAssetsUrl } from 'utils/utils';

export function getFonts() {
  return async (dispatch: Dispatch) => {
      dispatch({
        type: actionTypes.FONT_GET_LIST_START,
      });
      const result = await http.get<FontInfoFromServer[]>(api.fontList);

      if (result) {
        const mappedList = result.map((d) => ({
          name: d.name.replace(/\([\w\W]+\)/, '').split('.')[0],
          fullName: d.name,
          src: getAssetsUrl(`font/${d.name}`),
          create: d.updatedAt,
        }));
        addFontsByStyle(mappedList);

        dispatch({
          type: actionTypes.FONT_GET_LIST_SUCCESS,
          payload: {
            list: mappedList,
          },
        });
      } else {
        dispatch({
          type: actionTypes.FONT_GET_LIST_FAILURE,
        });
      }
  };
}

export function deleteFonts(fileList) {
  return async (dispatch) => {
    const result = await http.post(api.assetsDelete, {
      type: 'font',
      fileList,
    });

    if (result) {
      dispatch(getFonts());
      return result;
    }
  };
}

const initialState = {
  loading: true,
  list: [],
};

export default function reducer(state = initialState, { type, payload }) {
  switch (type) {
    case actionTypes.FONT_GET_LIST_START: {
      return { ...state, loading: true };
    }
    case actionTypes.FONT_GET_LIST_SUCCESS: {
      return { ...state, list: payload.list, loading: false };
    }
    case actionTypes.FONT_GET_LIST_FAILURE: {
      return { ...state, loading: false };
    }
    default:
      return state;
  }
}
