import _ from 'lodash';
import { Dispatch } from 'redux';
import { showToast, ToastType } from 'src/common/util/show-toast';
import { State } from 'src/redux/types';
import { performApiCall } from 'src/services/api';
import { AuthActionTypes } from 'src/services/auth';
import { transformApp } from '../transformations';

export enum AppActionTypes {
  FETCH_APPS = 'apps/fetch_apps',
  FETCH_APP = 'apps/fetch_app',
  UPDATE_APP = 'apps/update_app',
  CREATE_APP = 'apps/create_app',
  DELETE_APP = 'apps/delete_app',
  SET_APP_MODAL_LOADING = 'apps/app_modal_loading',
  SET_APPS_LOADING = 'apps/apps_loading',
  CREATE_BATCH_APPS = 'apps/create_batch_apps',
}

export const setAppsLoading = (isLoading: boolean) => (dispatch: Dispatch<any>) => {
  dispatch({
    type: AppActionTypes.SET_APPS_LOADING,
    payload: isLoading,
  });
};

export const setAppModalLoading = (isLoading: boolean) => (dispatch: Dispatch<any>) => {
  dispatch({
    type: AppActionTypes.SET_APP_MODAL_LOADING,
    payload: isLoading,
  });
};

export const fetchApps = () => async (dispatch: Dispatch<any>) => {
  dispatch(setAppsLoading(true));

  try {
    const { data } = await performApiCall({
      path: '/apps',
      method: 'GET',
    });

    dispatch({
      type: AppActionTypes.FETCH_APPS,
      payload: data.map(transformApp),
    });
  } catch (err) {
    console.error(err);
  }

  dispatch(setAppsLoading(false));
};

export const fetchAPPById = (id: string) => async (dispatch: Dispatch<any>) => {
  dispatch(setAppModalLoading(true));

  try {
    const { data } = await performApiCall({
      path: `/apps/${id}`,
      method: 'GET',
    });

    dispatch({
      type: AppActionTypes.FETCH_APP,
      payload: transformApp(data),
    });
  } catch (err) {
    console.error(err);
  }

  dispatch(setAppModalLoading(false));
};
