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

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


// start medical log fetch
const getDailyLogStart = () => ({
    type: DailyLogActionTypes.GET_USER_DAILY_LOGS_START
})


const getDailyLogSuccess = response => ({
    type: DailyLogActionTypes.GET_USER_DAILY_LOGS_SUCCESS,
    payload: response
})

const getDailyLogFailure = err => ({
    type: DailyLogActionTypes.GET_USER_DAILY_LOGS_FAILURE,
    payload: err
})

// start medical log fetch
const postDailyLogStart = () => ({
    type: DailyLogActionTypes.POST_USER_DAILY_LOGS_START
})


const postDailyLogSuccess = response => ({
    type: DailyLogActionTypes.POST_USER_DAILY_LOGS_SUCCESS,
    payload: response
})

const postDailyLogFailure = err => ({
    type: DailyLogActionTypes.POST_USER_DAILY_LOGS_FAILURE,
    payload: err
})

export const clearPostDailyLogState = () => ({
    type: DailyLogActionTypes.POST_USER_DAILY_LOGS_CLEAR_ERROR
})

export const clearGetDailyLogState = () => ({
    type: DailyLogActionTypes.DAILY_LOG_RESET_STATE
})
//report fetch
const getPatientDailyLogReportStart = () => ({
    type: DailyLogActionTypes.GET_DAILY_LOG_REPORT_START
})


const getPatientDailyLogReportSuccess = response => ({
    type: DailyLogActionTypes.GET_DAILY_LOG_REPORT_SUCCESS,
    payload: response
})

const getPatientDailyLogReportFailure = err => ({
    type: DailyLogActionTypes.GET_DAILY_LOG_REPORT_FAILURE,
    payload: err
})

//report ends
export const fetchDailyLogsAsync = (userId, selectedDate, page=1, sortColumn="LogTime", sortOrder="asc", numOfRecords=MettaSvr_Common.ITEMS_PER_PAGE) => {
    return async (dispatch, getState) => {
        dispatch(getDailyLogStart())
        try{
            const {user} = getState()                
            
            // return
            const {GET_USER_DAILY_LOGS} = METADATA_END_POINTS.patient
            const odataQuery = {
                top: numOfRecords,
                skip: numOfRecords * (page - 1),
                filter: {
                    LogDate: new Date(selectedDate)
                },
                count: true,
                orderBy: [`${sortColumn} ${sortOrder}`]
            }
            const query = buildQuery(odataQuery)
            const { CountKey, ValueKey } = MettaSvr_Common.ODATA_Keys
            const response = await withStore(user.currentUser.accessToken, dispatch).getService.get(`${GET_USER_DAILY_LOGS(userId)}${query}`)              
            dispatch(getDailyLogSuccess({count: response.data[CountKey], records: response.data[ValueKey]}))
            
        }catch(ex){            
            console.log("Error is: ", !!ex.response ? ex.response.data.errors : 'none')
            dispatch(getDailyLogFailure({message: ex.message ?? ex.response.data.title, apiResponseStatus: -1}))

        }
    }
}

export const saveDailyLogsAsync = (body, photoUploadReference = null) => {
    return async (dispatch, getState) => {
        dispatch(postDailyLogStart())
        try{
            const {user} = getState()                

            const {API_VERSION_V1, POST_USER_DAILY_LOGS} = METADATA_END_POINTS.patient
            const response = await withStore(user.currentUser.accessToken, dispatch).getService.post(`${API_VERSION_V1}${POST_USER_DAILY_LOGS}`,body)
            const {apiResponseStatus, errorMessage, title, result } = response.data
            if (apiResponseStatus === MettaSvr_Common.APIResponseStatus.Error){
                dispatch(postDailyLogFailure({message: errorMessage ?? title, apiResponseStatus}))
            }else{
                //if daily logs saved successfully, and there is photo upload waiting, we upload and then send the status as completed
                if(!!photoUploadReference){
                    dispatch(uploadPhoto(result, photoUploadReference))
                }else{
                    dispatch(postDailyLogSuccess(result))
                }
            }
        }catch(ex){            
            console.log("Error is: ", !!ex.response ? ex.response.data.errors : 'none')
            dispatch(postDailyLogFailure({message: ex.message ?? ex.response.data.title, apiResponseStatus: -1}))

        }
    }
}

const uploadPhoto =  (logId, fileReference) => {
    return async (dispatch, getState) => {
        const {user} = getState()                

        const fd = new FormData()
        fd.append("FormFile", fileReference)
        fd.append("logId", logId)
        const {UPLOAD_VERSION_V1, POST_USER_DAILY_LOGS_IMAGE_UPLOAD} = METADATA_END_POINTS.patient
        const {errorMessage,  apiResponseStatus} = await withStore(user.currentUser.accessToken, dispatch).getService.post(`${UPLOAD_VERSION_V1}${POST_USER_DAILY_LOGS_IMAGE_UPLOAD}`,fd)
        
        if (apiResponseStatus === MettaSvr_Common.APIResponseStatus.Error){
            dispatch(postDailyLogFailure({message: errorMessage }))
        }else{
            dispatch(postDailyLogSuccess(logId))
        }
    }
    
}

export const fetchDailyLogReportAsync = (patientId, columns=[], page=1, sortColumn="SubsCode", sortOrder="desc", numOfRecords=MettaSvr_Common.ITEMS_PER_PAGE) => {
    return async (dispatch, getState) => {
        try{
            dispatch(getPatientDailyLogReportStart())
            const {user} = getState()
            const { PATIENT_DAILY_LOG_REPORT } = METADATA_END_POINTS.common
            
            const odataQuery = {
                // top: numOfRecords,
                // skip: numOfRecords * (page - 1),                
                count: true,
                // orderBy: [`${sortColumn} ${sortOrder}`]
            }
            if(columns.length > 0){
                odataQuery["select"] = columns   
            }

            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_DAILY_LOG_REPORT}${query}`)              
            dispatch(getPatientDailyLogReportSuccess({count: response.data[CountKey], records: response.data[ValueKey]}))
            
        }catch(ex){            
            console.log("Error is: ", !!ex.response ? ex.response.data.errors : 'none')
            dispatch(getPatientDailyLogReportFailure({message: ex.response.data.message ?? ex.response.data.title, apiResponseStatus: -1}))

        }
    }
}