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


import { METADATA_END_POINTS } from '../../helpers/action-urls'
import {NotificationDetailLogTypes} from './notification-detail.action.type'
import {MettaSvr_Common} from '../../helpers/action-enums'

// start medical log fetch
const notificationDetailFetchStart = () => ({
    type: NotificationDetailLogTypes.NOTIFICATION_DETAIL_GET_MESSAGE_LIST_START
})


const notificationDetailFetchSuccess = response => ({
    type: NotificationDetailLogTypes.NOTIFICATION_DETAIL_GET_MESSAGE_LIST_SUCCESS,
    payload: response
})


const notificationDetailFetchFailure = err => ({
    type: NotificationDetailLogTypes.NOTIFICATION_DETAIL_GET_MESSAGE_LIST_FAILURE,
    payload: err
})

export const notificationDetailClearErrors = () => ({
    type: NotificationDetailLogTypes.NOTIFICATION_DETAIL_GET_MESSAGE_LIST_RESET_STATE,
    
})

/**
 * 
 * @param {*} recordInfo includes recordIndex and type of request(boolean): update or delete.
 * keys: recordIndex (int) and deleteRequest (boolean)
 * @returns 
 */
const notificationDetailPostStart = (recordInfo) => ({
    type: NotificationDetailLogTypes.NOTIFICATION_DETAIL_POST_MESSAGE_START,
    payload: recordInfo
})


const notificationDetailPostSuccess = response => ({
    type: NotificationDetailLogTypes.NOTIFICATION_DETAIL_POST_MESSAGE_SUCCESS,
    payload: response
})


const notificationDetailPostFailure = err => ({
    type: NotificationDetailLogTypes.NOTIFICATION_DETAIL_POST_MESSAGE_FAILURE,
    payload: err
})

export const getAllUserNotifcations = (notificationType, userId, page=1, sortColumn="CreatedOn", sortOrder="desc",numOfRecords=MettaSvr_Common.ITEMS_PER_PAGE) => {
    return async (dispatch, getState) => {
        dispatch(notificationDetailFetchStart())
        try{
            const {user} = getState()                

            const { GET_ALL_USER_NOTIFICATION } = METADATA_END_POINTS.common
            //notificationType eq ${notificationType}&$orderby=createdOn desc,isRead asc
            // const param1 = `notifyUser eq ${userId}`
            // const param2 = ` notificationType eq ${notificationType}`
            // const sortBy = 'createdOn desc,isRead asc'
            // const pageNum = `$skip=${pagesToSkip}`
            // const records = `$top=${numOfRecords}`
            const odataQuery = {
                top: numOfRecords,
                skip: numOfRecords * (page - 1),
                count: true,
                filter:{
                    NotifyUser: { eq: { type: 'guid', value: userId } },
                    NotificationType: parseInt(notificationType)
                },
                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_ALL_USER_NOTIFICATION}${query}`)  
            // const response = await axios.get(`${GET_ALL_USER_NOTIFICATION}?$filter=${encodeURIComponent(param2)}&$orderBy=${encodeURIComponent(sortBy)}`)  
            dispatch(notificationDetailFetchSuccess({count: response.data[CountKey], records: response.data[ValueKey]}))
  
            
        }catch(ex){            
            console.log("Error is: ", !!ex.response ? ex.response.data.errors : 'none')
            dispatch(notificationDetailFetchFailure({message: ex.message ?? `error fetching data due to ${ex.response.data.title}`}))

        }
        
    } 
}

export const updateNotificationAsync = (body) => {
    return async (dispatch, getState) => {
        //deletionRequest and indexOfRecord as set at component level. destructure only those two properties
        const { indexOfRecord, deletionRequest,...restOfBody} = body
        dispatch(notificationDetailPostStart({indexOfRecord, deletionRequest}))
        try{
            const {user} = getState()                

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

        }
    }
}