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

import buildQuery from 'odata-query'

import { SubscriptionCodeListActionTypes } from './susbcription-code-list.action.type'
import {METADATA_END_POINTS} from '../../helpers/action-urls'
import {MettaSvr_Common} from '../../helpers/action-enums'


// start medical log fetch
const getSubscriptionCodeListStart = () => ({
    type: SubscriptionCodeListActionTypes.GET_SUBSCRIPTION_CODE_LIST_START
})


const getSubscriptionCodeListSuccess = response => ({
    type: SubscriptionCodeListActionTypes.GET_SUBSCRIPTION_CODE_LIST_SUCCESS,
    payload: response
})

const getSubscriptionCodeListFailure = err => ({
    type: SubscriptionCodeListActionTypes.GET_SUBSCRIPTION_CODE_LIST_FAILURE,
    payload: err
})
//report fetch
const getSubscriptionCodeReportStart = () => ({
    type: SubscriptionCodeListActionTypes.GET_SUBSCRIPTION_CODE_REPORT_START
})


const getSubscriptionCodeReportSuccess = response => ({
    type: SubscriptionCodeListActionTypes.GET_SUBSCRIPTION_CODE_REPORT_SUCCESS,
    payload: response
})

const getSubscriptionCodeReportFailure = err => ({
    type: SubscriptionCodeListActionTypes.GET_SUBSCRIPTION_CODE_REPORT_FAILURE,
    payload: err
})

// start subscription post updates
const postSubscriptionCodeStart = (indexInfo) => ({
    type: SubscriptionCodeListActionTypes.SUBSCRIPTION_CODE_UPDATE_START,
    payload: indexInfo
})


const postSubscriptionCodeSuccess = response => ({
    type: SubscriptionCodeListActionTypes.SUBSCRIPTION_CODE_UPDATE_SUCCESS,
    payload: response
})

const postSubscriptionCodeFailure = err => ({
    type: SubscriptionCodeListActionTypes.SUBSCRIPTION_CODE_UPDATE_FAILURE,
    payload: err
})

export const clearGetSubscriptionCodeListState = () => ({
    type: SubscriptionCodeListActionTypes.SUBSCRIPTION_CODE_LIST_RESET_STATE
})

export const fetchSubscriptionCodeReportAsync = (columns=[], page=1, sortColumn="SubsCode", sortOrder="desc", numOfRecords=MettaSvr_Common.ITEMS_PER_PAGE) => {
    return async (dispatch, getState) => {
        try{
            dispatch(getSubscriptionCodeReportStart())
            const {user} = getState()
            const { SUBSCRIPTION_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
            }
            
            const query = buildQuery( odataQuery )
            
            const { CountKey, ValueKey } = MettaSvr_Common.ODATA_Keys
            const response = await withStore(user.currentUser.accessToken, dispatch).getService.get(`${SUBSCRIPTION_REPORT}${query}`)              
            dispatch(getSubscriptionCodeReportSuccess({count: response.data[CountKey], records: response.data[ValueKey]}))
            
        }catch(ex){            
            console.log("Error is: ", !!ex.response ? ex.response.data.errors : 'none')
            dispatch(getSubscriptionCodeReportFailure({message: ex.response.data.message ?? ex.response.data.title, apiResponseStatus: -1}))

        }
    }
}

export const fetchSubscriptionCodeListAsync = (page=1, sortColumn="SubsCode", sortOrder="desc", numOfRecords=MettaSvr_Common.ITEMS_PER_PAGE) => {
    return async (dispatch, getState) => {
        dispatch(getSubscriptionCodeListStart())
        try{

            const {user} = getState()
            const { SUBSCRIPTION_LIST } = METADATA_END_POINTS.common
            const odataQuery = {
                top: numOfRecords,
                skip: numOfRecords * (page - 1),
                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(`${SUBSCRIPTION_LIST}${query}`)              
            dispatch(getSubscriptionCodeListSuccess({count: response.data[CountKey], records: response.data[ValueKey]}))
            
        }catch(ex){            
            console.log("Error is: ", !!ex.response ? ex.response.data.errors : 'none')
            dispatch(getSubscriptionCodeListFailure({message: ex.response.data.message ?? ex.response.data.title, apiResponseStatus: -1}))

        }
    }
}

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

        dispatch(postSubscriptionCodeStart({indexOfRecord}))

        try{
            const {user} = getState()                

            const { API_VERSION_V1, UPDATE_SUBS_CODE } = METADATA_END_POINTS.auth
            const response = await withStore(user.currentUser.accessToken, dispatch).getService.post(`${API_VERSION_V1}${UPDATE_SUBS_CODE}`,restOfBody)
            const {apiResponseStatus, errorMessage } = response.data
            if (apiResponseStatus === MettaSvr_Common.APIResponseStatus.Error){
                dispatch(postSubscriptionCodeFailure({message: errorMessage, apiResponseStatus}))
            }else{
                const { SUBSCRIPTION_LIST } = METADATA_END_POINTS.common
                //fetch new results
                const filter = { SubscriptionId: { eq: { type: 'guid', value: restOfBody['SubscriptionId'] } } };                
                const query = buildQuery({ filter })
                const { ValueKey } = MettaSvr_Common.ODATA_Keys            
                const response = await withStore(user.currentUser.accessToken, dispatch).getService.get(`${SUBSCRIPTION_LIST}${query}`)              

                dispatch(postSubscriptionCodeSuccess(response.data[ValueKey][0]))
            }
        }catch(ex){            
            console.log("Error is: ", !!ex.response ? ex.response.data.errors : 'none')
            dispatch(postSubscriptionCodeFailure({message: ex.message ?? ex.response.data.title, apiResponseStatus: -1}))

        }
    }
}

