import React from 'react';
import * as breadcrumbsConstants from './BreadCrumbs.actionConstants';

export function stateReducer(state={active:'',visited:'',collapse:false}, action) {
    let stateJson=state
    switch (action.type) {
        case breadcrumbsConstants.ON_SELECT:
            stateJson.active=action.data.active
            stateJson.visited=action.data.visited
            return {...state,...stateJson}
        case breadcrumbsConstants.ON_COLLAPSE:
            stateJson.collapse=action.data.collapse
            return {...state,...stateJson}
        default:
            return stateJson
    }
}

export default function useBreadCrumb(initialValue,applyHook) {
    let [state,dispatchVal]=React.useReducer(stateReducer,{
        active:initialValue.active,
        visited:initialValue.active,
        collapse:initialValue.collapse
    })
    function onSelect(e,type,action){
        let modifiedState = {...state};
        modifiedState.active=e
        modifiedState.visited=e
        dispatchVal({type,data:modifiedState},action && action())
        if(applyHook){
            let newState=applyHook(state,modifiedState,type);
            dispatchVal({type,data:newState},action && action())
        }
    }
    
    function onCollapse(e,type,action){
        let modifiedState = {...state};
        modifiedState.collapse=!state.collapse
        dispatchVal({type,data:modifiedState},action && action())
        if(applyHook){
            let newState=applyHook(state,modifiedState,type);
            dispatchVal({type,data:newState},action && action())
        }
    }
    return [state.active,state.visited,onSelect,state.collapse,onCollapse]
}