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

import { GetShopFeaturedRequestModel, } from '../../models/requests'
import { GetShopFeaturedResponseModel } from '../../models/responses'
import { Get } from '../../restClient'

export interface ShopFeaturedState extends GetShopFeaturedResponseModel {
  isLoading: boolean
}

interface RequestAction extends GetShopFeaturedRequestModel {
  type: 'REQUEST_SHOP_FEATURED'
}

interface ReceiveAction extends GetShopFeaturedResponseModel {
  type: 'RECEIVE_SHOP_FEATURED'
}

type KnownAction = RequestAction | ReceiveAction

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

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

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

const unloadedState: ShopFeaturedState = {
  items: [
    {
      id: '',
      slug: "shop-catalog-item",
      sku: "SKU-0",
      image: { src: "https://dummyimage.com/450x300/dee2e6/6c757d.jpg", alt: "..." },
      badges: [ "sale" ],
      title: "Shop item title",
      brandName: "Brand & Name",

      shortText: "Lorem ipsum, dolor sit amet consectetur adipisicing elit. Eaque fugit ratione dicta mollitia. Officiis ad...",
      text: "",
      author: {
        id: '',
        image: { src: "https://dummyimage.com/40x40/ced4da/6c757d", alt: "..." },
        nickName: "Admin"
      },
      created: (new Date).toString(),

      tags: [ "react", "redux", "webapi" ],

      rating: 4.5,
      price: 20,
      newPrice: 10
    }
  ],
  isLoading: false
}

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

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

  return state
}
