import {UserActionTypes} from './action.types'
import {axios, withStore } from '../../services/AxiosInstance'
import {METADATA_END_POINTS} from '../helpers/action-urls'
import {MettaSvr_Common} from '../helpers/action-enums'


export const userLogOut = () => ({
    type: UserActionTypes.USER_LOGGED_OUT
})

// login user state changes
export const setCurrentUser = user => ({
    type: UserActionTypes.SET_CURRENT_USER,
    payload: user
})


const fetchUserStart = () => ({
    type: UserActionTypes.FETCH_USER_START
})

const fetchUserFailure = errorMessage => ({
    type: UserActionTypes.FETCH_USER_FAILURE,
    payload: errorMessage
})

const fetchUserSuccess = user => ({
    type: UserActionTypes.FETCH_USER_SUCCESS,
    payload: user
})

export const setSidebarState = () => ({
    type: UserActionTypes.SET_SIDEBAR_STATE,
})

export const clearAuthenticationState = () => ({
    type: UserActionTypes.POST_USER_CLEAR_STATE
})


//forgot password state changes
const postForgotPasswordStart = () => ({
    type: UserActionTypes.FORGOT_PASSWORD_START
})

const postForgotPasswordFailure = errorMessage => ({
    type: UserActionTypes.FORGOT_PASSWORD_FAILURE,
    payload: errorMessage
})

const postForgotPasswordSuccess = user => ({
    type: UserActionTypes.FORGOT_PASSWORD_SUCCESS,    
})

//change password state changes
const postChangePasswordStart = () => ({
    type: UserActionTypes.CHANGE_PASSWORD_START
})

const postChangePasswordFailure = errorMessage => ({
    type: UserActionTypes.CHANGE_PASSWORD_FAILURE,
    payload: errorMessage
})

const postChangePasswordSuccess = user => ({
    type: UserActionTypes.CHANGE_PASSWORD_SUCCESS,    
})
//profile image upload starts
const postProfilePicStart = () => ({
    type: UserActionTypes.POST_PROFILE_PIC_START
})

const postProfilePicSuccess = (response) => ({
    type: UserActionTypes.POST_PROFILE_PIC_SUCCESS,
    payload: response
})
//case history state changes

const postCaseHistoryStart = (currentValues) => ({
    type: UserActionTypes.POST_USER_CASE_HISTORY_LOGS_START,
    payload: currentValues
})

export const postCaseHistoryFailure = errorMessage => ({
    type: UserActionTypes.POST_USER_CASE_HISTORY_LOGS_FAILURE,
    payload: errorMessage
})

const postCaseHistorySuccess = response => ({
    type: UserActionTypes.POST_USER_CASE_HISTORY_LOGS_SUCCESS, 
    payload: response
})

const getUserMenuSuccess = response => ({
    type: UserActionTypes.GET_USER_MENU_SUCCESS, 
    payload: response
})

const fetchUserProfileStart = () => ({
    type: UserActionTypes.GET_USER_PROFILE_START,     
})

const fetchUserProfileSuccess = response => ({
    type: UserActionTypes.GET_USER_PROFILE_SUCCESS, 
    payload: response
})

export const clearFetchProfileState = () => ({
    type: UserActionTypes.CLEAR_USER_PROFILE_STATE,     
})

const postUserProfileStart = () => ({
    type: UserActionTypes.POST_USER_PROFILE_START,     
})

const postUserProfileSuccess = response => ({
    type: UserActionTypes.POST_USER_PROFILE_SUCCESS, 
    payload: response
})

const postUserFeedbackStart = () => ({
    type: UserActionTypes.POST_USER_FEEDBACK_START,     
})

const postUserFeedbackSuccess = response => ({
    type: UserActionTypes.POST_USER_FEEDBACK_SUCCESS, 
    payload: response
})

const postUserFeedbackFailure = response => ({
    type: UserActionTypes.POST_USER_FEEDBACK_ERROR, 
    payload: response
})

//terms and condition state changes
const postUserTermsAndConditionStart = () => ({
    type: UserActionTypes.POST_TERMS_ACCEPT_START,     
})

const postUserTermsAndConditionSuccess = () => ({
    type: UserActionTypes.POST_TERMS_ACCEPT_SUCCESS
})


const postUserTermsAndConditionFailure = response => ({
    type: UserActionTypes.POST_TERMS_ACCEPT_ERROR, 
    payload: response
})

//terms and condition state changes
const getUserTermsAndConditionStart = () => ({
    type: UserActionTypes.GET_TERMS_ACCEPT_START,     
})

const getUserTermsAndConditionSuccess = (content) => ({
    type: UserActionTypes.GET_TERMS_ACCEPT_SUCCESS,
    payload: content
})

export const submitTermsAndConditionAcceptanceAsync = (body) => {
    return async (dispatch, getState) => {
        try {

            dispatch(postUserTermsAndConditionStart())
            /*
            setTimeout(() => {
                // dispatch(postUserTermsAndConditionSuccess())
                dispatch(postUserTermsAndConditionFailure("wow error"))

            }, 5000)
           */
            const {user} = getState()                

            const {ACCEPT_TERMS_AND_CONDITIONS} = METADATA_END_POINTS.common
            const response = await withStore(user.currentUser.accessToken, dispatch).getService.post(ACCEPT_TERMS_AND_CONDITIONS,{})
            const {apiResponseStatus, errorMessage} = response.data
            if (apiResponseStatus === MettaSvr_Common.APIResponseStatus.Success){
                dispatch(postUserTermsAndConditionSuccess())
            }else{
                dispatch(postUserTermsAndConditionFailure(errorMessage))
            }
            
        } catch (ex) {
            console.log("Error is: ", ex)
            dispatch(postUserTermsAndConditionFailure( ex.response.data))    
        }
    }
}

export const submitCaseHistoryLogAsync = (body, latestValues) => {
    return async (dispatch, getState) => {
        try {
            const {user} = getState()                

            dispatch(postCaseHistoryStart(latestValues))
            const {API_VERSION_V1, MEDICAL_LOG} = METADATA_END_POINTS.patient
            const response = await withStore(user.currentUser.accessToken, dispatch).getService.post(API_VERSION_V1 + MEDICAL_LOG, body)
            const {apiResponseStatus, errorMessage, result} = response.data
            if (apiResponseStatus === MettaSvr_Common.APIResponseStatus.Success){
                dispatch(postCaseHistorySuccess(result))
            }else{
                dispatch(postCaseHistoryFailure(errorMessage))
            }
        }
        catch (ex) {
            console.log("Error is: ", ex)
            dispatch(postForgotPasswordFailure( ex.response.data.title))
        }
    }
}


export const forgotPasswordRequestAsync = (body) => {
    return async dispatch => {
        try {
            dispatch(postForgotPasswordStart())
            const {API_VERSION_V1, FORGOTPASSWORD_ENDPOINT} = METADATA_END_POINTS.auth
            const response = await axios.post(API_VERSION_V1 + FORGOTPASSWORD_ENDPOINT, body)
            const {apiResponseStatus, errorMessage} = response.data
            if (apiResponseStatus === MettaSvr_Common.APIResponseStatus.Success){
                dispatch(postForgotPasswordSuccess())
            }else{
                dispatch(postForgotPasswordFailure(errorMessage))
            }
        } catch (ex) {
            console.log("Error is: ", ex)
            dispatch(postForgotPasswordFailure( ex.response.data.title))    
        }
    }
}

export const changePasswordRequestAsync = (body) => {
    return async (dispatch, getState) => {
        try {
            dispatch(postChangePasswordStart())
            const {user} = getState()                

            const {API_VERSION_V1, RESETPASSWORD_ENDPOINT} = METADATA_END_POINTS.auth
            const response = await withStore(user.currentUser.accessToken, dispatch).getService.post(API_VERSION_V1 + RESETPASSWORD_ENDPOINT, body)
            const {apiResponseStatus, errorMessage} = response.data
            if (apiResponseStatus === MettaSvr_Common.APIResponseStatus.Success){
                dispatch(postChangePasswordSuccess())
            }else{
                dispatch(postChangePasswordFailure(errorMessage))
            }
        } catch (ex) {
            console.log("Error is: ", ex)
            dispatch(postChangePasswordFailure( ex.response.data))    
        }
    }
}

export const fetchUserRoleBasedMenuAsync = () => {
    return async (dispatch, getState) => {
        try{
            const {API_VERSION_V1, GET_MENU} = METADATA_END_POINTS.auth
            const {user} = getState()                
            const response = await withStore(user.currentUser.accessToken, dispatch).getService.get(API_VERSION_V1 + GET_MENU(user.currentUser.roleId))
            const {apiResponseStatus, errorMessage } = response.data
            if (apiResponseStatus !== MettaSvr_Common.APIResponseStatus.Success){
                dispatch(fetchUserFailure(errorMessage))
            }else{
                //get the access token as part of the header only during login. Rest of the time the feth works on the common
                //interceptors
                dispatch(getUserMenuSuccess(response.data["result"]))

            }
        }catch(ex){
            // debugger
            console.log("Error is: ", ex)
            dispatch(fetchUserFailure( ex.response.data.title))
        }
    }
}

export const fetchUserTermsAndConditionsAsync = () => {
    return async (dispatch) => {
        try{
            dispatch(getUserTermsAndConditionStart)
            const {READ_TERMS_AND_CONDITIONS} = METADATA_END_POINTS.admin
            const response = await axios.get(READ_TERMS_AND_CONDITIONS)
            const {apiResponseStatus, errorMessage } = response.data
            if (apiResponseStatus !== MettaSvr_Common.APIResponseStatus.Success){
                dispatch(fetchUserFailure(errorMessage))
            }else{
                //get the access token as part of the header only during login. Rest of the time the feth works on the common
                //interceptors
                // console.log("hello world ",response.data["result"])
                dispatch(getUserTermsAndConditionSuccess(response.data["result"]))
                // dispatch(getUserMenuSuccess(response.data["result"]))

            }
        }catch(ex){
            // debugger
            console.log("Error is: ", ex)
            dispatch(fetchUserFailure( ex.response.data.title))
        }
    }
}

export const fetchUserProfileAsync = (userId=null) => {
    return async (dispatch, getState) => {
        try{
            dispatch(fetchUserProfileStart())

            const {GET_USER_PROFILE, GET_USER_PROFILE_BY_ID} = METADATA_END_POINTS.admin
            const {user} = getState()                
            const theUrl = !!userId ? `${GET_USER_PROFILE_BY_ID}/${userId}` : GET_USER_PROFILE
            const response = await withStore(user.currentUser.accessToken, dispatch).getService.get(theUrl)
            const {apiResponseStatus, errorMessage, result} = response.data
            if (apiResponseStatus !== MettaSvr_Common.APIResponseStatus.Success){
                dispatch(fetchUserFailure(errorMessage))
            }else{
                //get the access token as part of the header only during login. Rest of the time the feth works on the common
                //interceptors
                dispatch(fetchUserProfileSuccess(result))

            }
        }catch(ex){
            // debugger
            console.log("Error is: ", ex)
            dispatch(fetchUserFailure( ex.response.data.title))
        }
    }
}

export const submitUserProfileAsync = (body) => {
    return async (dispatch, getState) => {
        try {
            const {user} = getState()                

            dispatch(postUserProfileStart())
            const {UPDATE_USER_PROFILE} = METADATA_END_POINTS.admin
            const response = await withStore(user.currentUser.accessToken, dispatch).getService.post(UPDATE_USER_PROFILE, body)
            const {apiResponseStatus, errorMessage, result} = response.data
            if (apiResponseStatus === MettaSvr_Common.APIResponseStatus.Success){
                dispatch(postUserProfileSuccess(result))
            }else{
                dispatch(fetchUserFailure(errorMessage))
            }
        }
        catch (ex) {
            console.log("Error is: ", ex)
            dispatch(fetchUserFailure( ex.response.data.title))    
        }
    }
}

export const submitWorkInformationAsync = (body) => {
    return async (dispatch, getState) => {
        try {
            const {user} = getState()                

            dispatch(postUserProfileStart())
            const {UPDATE_USER_PROFILE_WORK_INFO} = METADATA_END_POINTS.admin
            const response = await withStore(user.currentUser.accessToken, dispatch).getService.post(UPDATE_USER_PROFILE_WORK_INFO, body)
            const {apiResponseStatus, errorMessage, result} = response.data
            if (apiResponseStatus === MettaSvr_Common.APIResponseStatus.Success){
                dispatch(postUserProfileSuccess(result))
            }else{
                dispatch(fetchUserFailure(errorMessage))
            }
        }
        catch (ex) {
            console.log("Error is: ", ex)
            dispatch(fetchUserFailure( ex.response.data.title))    
        }
    }
}

export const submitUserFeedbackAsync = (body) => {
    return async (dispatch, getState) => {
        try {
            const {user} = getState()                

            dispatch(postUserFeedbackStart())
            const {UPDATE_USER_FEEDBACK} = METADATA_END_POINTS.admin
            const response = await withStore(user.currentUser.accessToken, dispatch).getService.post(UPDATE_USER_FEEDBACK, body)
            const {apiResponseStatus, errorMessage, result} = response.data
            if (apiResponseStatus === MettaSvr_Common.APIResponseStatus.Success){
                dispatch(postUserFeedbackSuccess(result))
            }else{
                dispatch(postUserFeedbackFailure(errorMessage))
            }
        }
        catch (ex) {
            console.log("Error is: ", ex)
            dispatch(postUserFeedbackFailure( ex.response.data.title))    
        }
    }
}

export const authenticateUserAsync = (body) => {
    return async (dispatch) => {
        dispatch(fetchUserStart())
        try{
            // dispatch(postPatientFailure(testErroObject()))
            // dispatch(patientRegistrationAndPaymentCompleted(testSuccessObject()))

            // return
            const {API_VERSION_V1, LOGIN_ENDPOINT} = METADATA_END_POINTS.auth
            const response = await axios.post(API_VERSION_V1 + LOGIN_ENDPOINT, body)
            const {apiResponseStatus, errorMessage, result} = response.data
            if (apiResponseStatus !== MettaSvr_Common.APIResponseStatus.Success){
                dispatch(fetchUserFailure(errorMessage))
            }else{
                //get the access token as part of the header only during login. Rest of the time the feth works on the common
                //interceptors
                const authToken = response.headers["cat"]
                dispatch(fetchUserSuccess({...result, accessToken: authToken}))
            }
        }catch(ex){
            // debugger
            console.log("Error is: ", ex)
            dispatch(fetchUserFailure( ex.response.data.title))
        }

    }
    
}

//upload profile photo.
export const uploadProfilePhoto =  (fileReference) => {
    return async (dispatch, getState) => {
        try{
            
            dispatch(postProfilePicStart())
            const {user} = getState()                

            const fd = new FormData()
            fd.append("file", fileReference)

            const {UPLOAD_PROFILE_PIC} = METADATA_END_POINTS.auth
            const response = await withStore(user.currentUser.accessToken, dispatch).getService.post(`${UPLOAD_PROFILE_PIC}`,fd)
            const {errorMessage,  apiResponseStatus, result } = response.data
            
            if (apiResponseStatus === MettaSvr_Common.APIResponseStatus.Error){
                dispatch(fetchUserFailure({message: errorMessage }))
            }else{
                dispatch(postProfilePicSuccess(result))
            }
        }catch(ex){
            // debugger
            console.log("Error is: ", ex)
            dispatch(fetchUserFailure( {message: ex.response.data.title}))
        }
    }
    
}