import { Buffer } from 'buffer'
import { UserActionTypes } from './action.types'
import { MettaSvr_Common } from '../helpers/action-enums'

const INITIAL_STATE = {
    currentUser: null,
    isFetching: false,
    errorMessage: undefined,
    sidebarOpen: false,   
    forgotPasswordRequestCompletedSuccessfully: false,
    changePasswordRequestCompletedSuccessfully: false,
    feedbackSubmittedSuccessfully: false,
    showCaseHistory: false,
    initialValues: null,
    //used by profile photo upload
    submissionInProgress: false,
    saveResult: null,
    profileDataSaveResult: null,
    termsContent: null,
    //ends
    caseHistorySubmittedSuccess: undefined //helps in page navigation amongst the case history tabs
}

const userReducer = (currentState = INITIAL_STATE, action) => {
    switch(action.type){
        case UserActionTypes.FETCH_USER_START:
            return {
                ...currentState,
                errorMessage: null,
                isFetching: true
            }
            //profile image upload
        case UserActionTypes.POST_PROFILE_PIC_START:
            return {
                ...currentState,
                submissionInProgress: true
            }
        case UserActionTypes.POST_PROFILE_PIC_SUCCESS:{
            const updatedState = {...currentState}
            updatedState.currentUser.profilePhotoUrl = action.payload
            updatedState.currentUser.profile.profilePhotoUrl = action.payload
            return{
                ...updatedState,
                submissionInProgress: false,
                errorMessage: null,
                saveResult: action.payload
            }
        }
            //
            /*
            for testing:
            currentUser: {...action.payload, ShowMedicalLogForm: true},
                showCaseHistory: true
                // (ShowAlcoholForm || ShowDepressionForm || ShowErectileForm || ShowMedicalLogForm || ShowSmokingForm),
            */
        case UserActionTypes.FETCH_USER_SUCCESS: {
            const {showAlcoholForm,showDepressionForm,
                showErectileForm,
                showMedicalLogForm,
                showSmokingForm,
                userType
            } = action.payload
            return {
                ...currentState,
                isFetching: false,
                currentUser: action.payload,
                showCaseHistory: (userType === MettaSvr_Common.UserTypeEnum.Patients) && (showAlcoholForm || showDepressionForm || showErectileForm || showMedicalLogForm || showSmokingForm),               
            }
        }
        case UserActionTypes.FETCH_USER_FAILURE: 
            return{
                ...currentState,
                isFetching: false,
                submissionInProgress: false,
                errorMessage: action.payload
            }
        case UserActionTypes.SET_CURRENT_USER:
            return {
                ...currentState,
                currentUser: action.payload
            }
        case UserActionTypes.SET_SIDEBAR_STATE:
            return {
                ...currentState,
                sidebarOpen: !currentState.sidebarOpen
            }
        case UserActionTypes.POST_USER_CLEAR_STATE: 
            return {
                ...currentState,
                errorMessage: null,
                changePasswordRequestCompletedSuccessfully: false,
                forgotPasswordRequestCompletedSuccessfully: false,
                isFetching: false,
                saveResult: null,
                profileDataSaveResult: null,
                submissionInProgress: false,
                feedbackSubmittedSuccessfully: false

            }
        case UserActionTypes.UPDATE_ACCESS_TOKEN: 
        {
            const updatedCurrentUser = { ...currentState.currentUser, accessToken: action.payload }
            return {
                ...currentState,
                currentUser: updatedCurrentUser
            }
        }
        case UserActionTypes.GET_USER_MENU_SUCCESS:
            {
                //transform the payload into object. As the lnk_url consists of the key.
                const menuList = action.payload
                const menuAsObject = menuList.reduce((acc, curr) =>  {
                    acc[curr["link_url"]] = curr
                    return acc
                }, {})
                const updatedCurrentUser = { ...currentState.currentUser, menu: menuAsObject }
                return {
                    ...currentState,
                    currentUser: updatedCurrentUser
                } 
            }
/** case history form submission block */            
        case UserActionTypes.POST_USER_CASE_HISTORY_LOGS_FAILURE:
            return {
                ...currentState,
                isFetching: false,
                errorMessage: action.payload,
                caseHistorySubmittedSuccess: false
            }
        case UserActionTypes.POST_USER_CASE_HISTORY_LOGS_SUCCESS:{
            const {showAlcoholForm,showDepressionForm,
                showErectileForm,
                showMedicalLogForm,
                showSmokingForm} = action.payload
            const newUserInfo = {
                currentUser:{
                    ...currentState.currentUser,
                    ...action.payload
                },
                showCaseHistory: (showAlcoholForm || showDepressionForm || showErectileForm || showMedicalLogForm || showSmokingForm),               
            }

            return {
                ...currentState,
                ...newUserInfo,
                isFetching: false,                
                initialValues: null,
                caseHistorySubmittedSuccess: true
            }
        }
        case UserActionTypes.POST_USER_CASE_HISTORY_LOGS_START:
            return {
                ...currentState,
                isFetching: true,            
                initialValues: action.payload,
                caseHistorySubmittedSuccess: false
    
            }
            
/** forgot password */            
        case UserActionTypes.FORGOT_PASSWORD_START:
            return {
                ...currentState,
                isFetching: true
            }
        case UserActionTypes.FORGOT_PASSWORD_SUCCESS:
            return {
                ...currentState,
                isFetching: false,
                forgotPasswordRequestCompletedSuccessfully: true

            }
        case UserActionTypes.FORGOT_PASSWORD_FAILURE:
            return {
                ...currentState,
                isFetching: false,
                forgotPasswordRequestCompletedSuccessfully: false,
                errorMessage: action.payload
            }
/** change password */            
        case UserActionTypes.CHANGE_PASSWORD_START:
            return {
                ...currentState,
                isFetching: true
            }
        case UserActionTypes.CHANGE_PASSWORD_SUCCESS:
            return {
                ...currentState,
                isFetching: false,
                changePasswordRequestCompletedSuccessfully: true

            }
        case UserActionTypes.CHANGE_PASSWORD_FAILURE:
            return {
                ...currentState,
                isFetching: false,
                changePasswordRequestCompletedSuccessfully: false,
                errorMessage: action.payload
            }

        case UserActionTypes.GET_USER_PROFILE_START:
            return{
                ...currentState,
                isFetching: true,
            }

        case UserActionTypes.GET_USER_PROFILE_SUCCESS:{
            const updatedCurrentUser = { ...currentState.currentUser }
            updatedCurrentUser["profile"] = action.payload

            return{
                ...currentState,
                currentUser: updatedCurrentUser,
                isFetching: false,
            }
        }
       
        case UserActionTypes.POST_USER_PROFILE_START:
            return{
                ...currentState,
                submissionInProgress: true,
            }

        case UserActionTypes.POST_USER_PROFILE_SUCCESS:{
            return{
                ...currentState,
                submissionInProgress: false,
                profileDataSaveResult: true,                
            }
        }

        case UserActionTypes.CLEAR_USER_PROFILE_STATE:{
            const updatedCurrentUser = { ...currentState.currentUser }
            //logged out
            if (Object.keys(updatedCurrentUser).length === 0)
                return INITIAL_STATE
            updatedCurrentUser["profile"] = null

            return {
                ...currentState,
                currentUser: updatedCurrentUser,
                isFetching: false,

            }
        }
    case UserActionTypes.POST_USER_FEEDBACK_START:{
        return {
            ...currentState,
            submissionInProgress: true,
            feedbackSubmittedSuccessfully: false
        
        }
    }
    case UserActionTypes.POST_USER_FEEDBACK_SUCCESS:{
        return {
            ...currentState,
            submissionInProgress: false,
            feedbackSubmittedSuccessfully: true,
            saveResult: action.payload,        
        }
    }
    case UserActionTypes.POST_USER_FEEDBACK_ERROR:{
        return {
            ...currentState,
            submissionInProgress: false,
            saveResult: null,
            errorMessage: action.payload,
            feedbackSubmittedSuccessfully: false
        }

    }
/**
 * terms and condition states
 */
    case UserActionTypes.POST_TERMS_ACCEPT_START:{
        return{
            ...currentState,
            submissionInProgress: true
        }
        
    }
    case UserActionTypes.POST_TERMS_ACCEPT_SUCCESS:{
        const updatedCurrentUser = { ...currentState.currentUser }
        updatedCurrentUser["isTermsConditionNeedToAgree"] = false
        return{
            ...currentState,
            currentUser: updatedCurrentUser,  
            submissionInProgress: false
        }
        
    }
    case UserActionTypes.POST_TERMS_ACCEPT_ERROR:{
        return{
            ...currentState,
            submissionInProgress: false,
            errorMessage: action.payload
        }
        
    }
    // Fetch terms condiiton content
    case UserActionTypes.GET_TERMS_ACCEPT_START:{
        return{
            ...currentState,
            isFetching: true
        }
        
    }
    case UserActionTypes.GET_TERMS_ACCEPT_SUCCESS:{
        let base64ToString = Buffer.from(action.payload, "base64").toString();

        return{
            ...currentState,
            termsContent: base64ToString,  
            isFetching: false
        }
        
    }
/** reset password */            
/** nav testing in case history. dispatch following case from redux tools to check. */            
/*
            sample dispatch body:
            {
                type: 'test_nav',
                payload:{
                    nav: {
                        ShowAlcoholForm: false,
                        ShowDepressionForm: false,
                        ShowErectileForm: true, 
                        ShowMedicalLogForm: true,
                        ShowSmokingForm: true
                    },
                    rest: false
                }
            }
*/
    case 'test_nav':
        return {
            ...currentState,
            currentUser:{
                ...currentState.currentUser,
                ...action.payload['nav']
            },
            caseHistorySubmittedSuccess: action.payload['rest']

        }

        default:
            return currentState
    }
}


export default userReducer