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

import buildQuery from 'odata-query'

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


// start medical log fetch
const getPatientListStart = () => ({
    type: PatientListActionTypes.GET_PATIENT_LIST_START
})


const getPatientListSuccess = response => ({
    type: PatientListActionTypes.GET_PATIENT_LIST_SUCCESS,
    payload: response
})

const getPatientListFailure = err => ({
    type: PatientListActionTypes.GET_PATIENT_LIST_FAILURE,
    payload: err
})

const postUpdatePatientStatusStart = (indexInfo) => ({
    type: PatientListActionTypes.UPDATE_PATIENT_START,
    payload: indexInfo
})


const postUpdatePatientStatusSuccess = response => ({
    type: PatientListActionTypes.UPDATE_PATIENT_SUCCESS,
    payload: response
})

const postUpdatePatientStatusFailure = err => ({
    type: PatientListActionTypes.UPDATE_PATIENT_FAILURE,
    payload: err
})


export const setTargetPatientToUpdate = (patientId) => ({
    type: PatientListActionTypes.SET_TARGET_PATIENT,
    payload: patientId
})

export const clearPatientListErrorState = () => ({
    type: PatientListActionTypes.PATIENT_LIST_CLEAR_ERROR_STATE
})

export const clearGetPatientListState = () => ({
    type: PatientListActionTypes.PATIENT_LIST_RESET_STATE
})

export const fetchPatientListsAsync = (page=1, sortColumn="PatientName", sortOrder="desc", numOfRecords=MettaSvr_Common.ITEMS_PER_PAGE) => {
    return async (dispatch, getState) => {
        dispatch(getPatientListStart())
        try{

            const {user} = getState()
            const { PATIENT_LIST } = METADATA_END_POINTS.common
            const odataQuery = {
                top: numOfRecords,
                skip: numOfRecords * (page - 1),
                count: true,
                orderBy: [`${sortColumn} ${sortOrder}`],
                // filter:{
                //     IsActive: true
                // },
            }
            
            const query = buildQuery( odataQuery )
            const { CountKey, ValueKey } = MettaSvr_Common.ODATA_Keys
            const response = await withStore(user.currentUser.accessToken, dispatch).getService.get(`${PATIENT_LIST}${query}`)              
            dispatch(getPatientListSuccess({count: response.data[CountKey], records: response.data[ValueKey]}))
            
        }catch(ex){            
            console.log("Error is: ", !!ex.response ? ex.response.data.errors : 'none')
            dispatch(getPatientListFailure({message: ex.response.data.message ?? ex.response.data.title, apiResponseStatus: -1}))

        }
    }
}

export const updatePatientCriticallityStatusAsync = (body) => {
    return async (dispatch, getState) => {
        const { indexOfRecord, ...restOfBody} = body

        dispatch(postUpdatePatientStatusStart({indexOfRecord}))

        try{
            const {user} = getState()                

            const { UPDATE_PATIENT_CRITICAL_STATUS } = METADATA_END_POINTS.admin
            const response = await withStore(user.currentUser.accessToken, dispatch).getService.post(`${UPDATE_PATIENT_CRITICAL_STATUS}`,restOfBody)
            const {apiResponseStatus, errorMessage } = response.data
            if (apiResponseStatus === MettaSvr_Common.APIResponseStatus.Error){
                dispatch(postUpdatePatientStatusFailure({message: errorMessage, apiResponseStatus}))
            }else{
                dispatch(postUpdatePatientStatusSuccess({fieldName:"CriticalityStatus" , updatedValue: restOfBody['CriticalityStatus']}))
            }
        }catch(ex){            
            console.log("Error is: ", !!ex.response ? ex.response.data.errors : 'none')
            dispatch(postUpdatePatientStatusFailure({message: ex.message ?? ex.response.data.title, apiResponseStatus: -1}))

        }
    }
}

export const updatePatientStatusAsync = (body) => {
    return async (dispatch, getState) => {
        const { indexOfRecord, ...restOfBody} = body

        dispatch(postUpdatePatientStatusStart({indexOfRecord}))

        try{
            const {user} = getState()                

            const { UPDATE_PATIENT_STATUS } = METADATA_END_POINTS.admin
            const response = await withStore(user.currentUser.accessToken, dispatch).getService.post(`${UPDATE_PATIENT_STATUS}`,restOfBody)
            const {apiResponseStatus, errorMessage } = response.data
            if (apiResponseStatus === MettaSvr_Common.APIResponseStatus.Error){
                dispatch(postUpdatePatientStatusFailure({message: errorMessage, apiResponseStatus}))
            }else{                
                dispatch(postUpdatePatientStatusSuccess({fieldName:"Status" , updatedValue: restOfBody['IsActive']}))
                
            }
        }catch(ex){            
            console.log("Error is: ", !!ex.response ? ex.response.data.errors : 'none')
            dispatch(postUpdatePatientStatusFailure({message: ex.message ?? ex.response.data.title, apiResponseStatus: -1}))

        }
    }
}