import { Action, Reducer } from 'redux'
import { AppThunkAction } from '../'

import { GetShopCategoriesRequestModel } from '../../models/requests'
import { GetShopCategoriesResponseModel } from '../../models/responses'
import { Get } from '../../restClient'

export interface ShopCategoriesState extends GetShopCategoriesResponseModel {
  isLoading: boolean
}

interface RequestAction extends GetShopCategoriesRequestModel {
  type: 'REQUEST_SHOP_CATEGORIES'
}

interface ReceiveAction extends GetShopCategoriesResponseModel {
  type: 'RECEIVE_SHOP_CATEGORIES'
}

type KnownAction = RequestAction | ReceiveAction

export const actionCreators = {
  requestShopCategories: (props?: GetShopCategoriesRequestModel): AppThunkAction<KnownAction> => (dispatch, getState) => {

    Get<Promise<GetShopCategoriesResponseModel>>('https://localhost:7151/api/ShopCategories', props?.pathParams, props?.searchParams)
      .then(response => response)
      .then(data => {
        if(data)
          dispatch({ type: 'RECEIVE_SHOP_CATEGORIES', ...data })
      })

    dispatch({ type: 'REQUEST_SHOP_CATEGORIES' })
  }
}

const unloadedState: ShopCategoriesState = {
  items: [
    { id: "", text: "Software" },
    { id: "", text: "Hardware" }
  ],
  isLoading: false
}

export const reducer: Reducer<ShopCategoriesState> = (state: ShopCategoriesState | undefined, incomingAction: Action): ShopCategoriesState => {
  if (state === undefined) {
    return unloadedState
  }
  
  const action = incomingAction as KnownAction
  switch (action.type) {
    case 'REQUEST_SHOP_CATEGORIES':
      return {
        ...state,
        isLoading: true
      }

    case 'RECEIVE_SHOP_CATEGORIES':
      return {
        ...action,
        isLoading: false
      }
  }

  return state
}
