import {withStore } from '../../../services/AxiosInstance'
import buildQuery from 'odata-query'

import { MedicalLogTypes } from './medical-logs.action.types'
import {METADATA_END_POINTS} from '../../helpers/action-urls'
import {MettaSvr_Common} from '../../helpers/action-enums'


// start medical log fetch
const getMedicalLogStart = () => ({
    type: MedicalLogTypes.GET_USER_MEDICAL_HISTORY_LOGS_START
})


const getMedicalLogSuccess = response => ({
    type: MedicalLogTypes.GET_USER_MEDICAL_HISTORY_LOGS_SUCCESS,
    payload: response
})

const getMedicalLogFailure = err => ({
    type: MedicalLogTypes.GET_USER_MEDICAL_HISTORY_LOGS_FAILURE,
    payload: err
})


export const clearGetMedicalLogState = () => ({
    type: MedicalLogTypes.MEDICAL_LOG_RESET_STATE
})

//report fetch
const getMedicalLogReportStart = () => ({
    type: MedicalLogTypes.GET_USER_MEDICAL_HISTORY_LOGS_REPORT_START
})


const getMedicalLogReportSuccess = response => ({
    type: MedicalLogTypes.GET_USER_MEDICAL_HISTORY_LOGS_REPORT_SUCCESS,
    payload: response
})

const getMedicalLogReportFailure = err => ({
    type: MedicalLogTypes.GET_USER_MEDICAL_HISTORY_LOGS_REPORT_FAILURE,
    payload: err
})

//report ends

export const fetchMedicalLogsAsync = (userId) => {
    return async (dispatch, getState) => {
        dispatch(getMedicalLogStart())
        try{

            const {user} = getState()                
            // return
            const {API_VERSION_V1, GET_MEDICAL_LOG} = METADATA_END_POINTS.patient
            const response = await withStore(user.currentUser.accessToken, dispatch).getService.get(`${API_VERSION_V1}${userId}/${GET_MEDICAL_LOG}`)
            const {apiResponseStatus, errorMessage, title, result } = response.data
            if (apiResponseStatus === MettaSvr_Common.APIResponseStatus.Error){
                dispatch(getMedicalLogFailure({message: errorMessage ?? title, apiResponseStatus}))
            }else{
                dispatch(getMedicalLogSuccess(result))
            }
        }catch(ex){            
            console.log("Error is: ", !!ex.response ? ex.response.data.errors : 'none')
            dispatch(getMedicalLogFailure({message: ex.message ?? ex.response.data.title, apiResponseStatus: -1}))

        }
    }
}

export const fetchMedicalLogReportAsync = (patientId, page=1, sortColumn="SubsCode", sortOrder="desc", numOfRecords=MettaSvr_Common.ITEMS_PER_PAGE) => {
    return async (dispatch, getState) => {
        try{
            dispatch(getMedicalLogReportStart())
            const {user} = getState()
            const { PATIENT_MEDICAL_HISTORY_REPORT } = METADATA_END_POINTS.common
            
            const odataQuery = {
                // top: numOfRecords,
                // skip: numOfRecords * (page - 1),                
                count: true,
                // orderBy: [`${sortColumn} ${sortOrder}`]
            }
            var extraQuery = null 
            if(!!patientId) {
                extraQuery = {
                    ...odataQuery,
                    filter: {
                        PatientId: { eq: { type: 'guid', value: patientId } },
                    },
                }
            }
            const query = buildQuery( extraQuery ?? odataQuery )
            
            const { CountKey, ValueKey } = MettaSvr_Common.ODATA_Keys
            const response = await withStore(user.currentUser.accessToken, dispatch).getService.get(`${PATIENT_MEDICAL_HISTORY_REPORT}${query}`)              
            dispatch(getMedicalLogReportSuccess({count: response.data[CountKey], records: response.data[ValueKey]}))
            
        }catch(ex){            
            console.log("Error is: ", !!ex.response ? ex.response.data.errors : 'none')
            dispatch(getMedicalLogReportFailure({message: ex.response.data.message ?? ex.response.data.title, apiResponseStatus: -1}))

        }
    }
}