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

import { GetBlogCategoriesRequestModel } from '../../models/requests'
import { GetBlogCategoriesResponseModel } from '../../models/responses'
import { Get } from '../../restClient'

export interface BlogCategoriesState extends GetBlogCategoriesResponseModel {
  isLoading: boolean
}

interface RequestAction extends GetBlogCategoriesRequestModel {
  type: 'REQUEST_BLOG_CATEGORIES'
}

interface ReceiveAction extends GetBlogCategoriesResponseModel {
  type: 'RECEIVE_BLOG_CATEGORIES'
}

type KnownAction = RequestAction | ReceiveAction

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

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

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

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

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

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

  return state
}
