import { withStore } from '../../../services/AxiosInstance'

import buildQuery from 'odata-query'

import { EducatorListActionTypes } from './educator-list.action.type'
import {METADATA_END_POINTS} from '../../helpers/action-urls'
import {MettaSvr_Common} from '../../helpers/action-enums'


// start medical log fetch
const getEducatorListStart = () => ({
    type: EducatorListActionTypes.GET_EDUCATOR_LIST_START
})


const getEducatorListSuccess = response => ({
    type: EducatorListActionTypes.GET_EDUCATOR_LIST_SUCCESS,
    payload: response
})

const getEducatorListFailure = err => ({
    type: EducatorListActionTypes.GET_EDUCATOR_LIST_FAILURE,
    payload: err
})

export const clearGetEducatorListState = () => ({
    type: EducatorListActionTypes.EDUCATOR_LIST_RESET_STATE
})

export const clearEducatorListErrorState = () => ({
    type: EducatorListActionTypes.EDUCATOR_STATUS_CLEAR_ERROR_STATE
})

/** post of educator status */
const educatorStatusUpdatePostStart = (recordInfo) => ({
    type: EducatorListActionTypes.EDUCATOR_STATUS_POST_MESSAGE_START,
    payload: recordInfo
})


const postEducatorStateSuccess = response => ({
    type: EducatorListActionTypes.EDUCATOR_STATUS_POST_MESSAGE_SUCCESS,
    payload: response
})


const postEducatorStateFailure = err => ({
    type: EducatorListActionTypes.EDUCATOR_STATUS_POST_MESSAGE_FAILURE,
    payload: err
})



export const postEducatorStateAsync = (body) => {
    return async (dispatch, getState) => {

        const { indexOfRecord, ...restOfBody} = body
        dispatch(educatorStatusUpdatePostStart({indexOfRecord}))
        try{
            const {user} = getState()                

            const { UPDATE_EDUCATOR_STATUS } = METADATA_END_POINTS.admin
            const response = await withStore(user.currentUser.accessToken, dispatch).getService.post(`${UPDATE_EDUCATOR_STATUS}`,restOfBody)
            const {apiResponseStatus, errorMessage, result } = response.data
            if (apiResponseStatus === MettaSvr_Common.APIResponseStatus.Error){
                dispatch(postEducatorStateFailure({message: errorMessage, apiResponseStatus}))
            }else{
                dispatch(postEducatorStateSuccess(result))
            }
        }catch(ex){            
            console.log("Error is: ", !!ex.response ? ex.response.data.errors : 'none')
            dispatch(postEducatorStateFailure({message: ex.message ?? ex.response.data.title, apiResponseStatus: -1}))

        }
    }
}

export const fetchEducatorListAsync = (page=1, filter=null, sortColumn="FirstName", sortOrder="desc", numOfRecords=MettaSvr_Common.ITEMS_PER_PAGE) => {
    return async (dispatch, getState) => {
        dispatch(getEducatorListStart())
        try{

            const {user} = getState()
            const { EDUCATOR_LIST } = METADATA_END_POINTS.common
            const odataQuery = {
                top: numOfRecords,
                skip: numOfRecords * (page - 1),
                count: true,
                orderBy: [`${sortColumn} ${sortOrder}`],                
            }
            var extraQuery = null 
            if (!!filter){
                extraQuery = {
                    ...odataQuery,
                    filter: filter
                }
            }

            const query = buildQuery( extraQuery ?? odataQuery )
            const { CountKey, ValueKey } = MettaSvr_Common.ODATA_Keys
            const response = await withStore(user.currentUser.accessToken, dispatch).getService.get(`${EDUCATOR_LIST}${query}`)              
            dispatch(getEducatorListSuccess({count: response.data[CountKey], records: response.data[ValueKey]}))
            
        }catch(ex){            
            console.log("Error is: ", !!ex.response ? ex.response.data.errors : 'none')
            dispatch(getEducatorListFailure({message: ex.response.data.message ?? ex.response.data.title, apiResponseStatus: -1}))

        }
    }
}

