import {createContext, useContext, useReducer} from "react";

const CombsContext = createContext({});
const CombsDispatchContext = createContext(() => {
});

function compareCombs(a, b) {
    for (const keys of Object.keys(a)) {
        if (a[keys] !== b[keys]) {
            return false;
        }
    }
    return true;
}

function reducer(state, action) {
    switch (action.type) {
        case 'SET_COMB':
            if (state[action.payload.id] === undefined || !compareCombs(state[action.payload.id], action.payload)) {
                console.debug("Updating comb", action.payload);
                return {
                    ...state,
                    [action.payload.id]: action.payload.value
                }
            }
            return state
        case 'SET_ALL':
            // By default, we only update some fields to avoid overwriting with incomplete data
            const combs = (action.payload.source === "register") ? action.payload.data : action.payload.data.map(e => {
                return {
                    id: e.id,
                    fname: e.fname,
                    lname: e.lname,
                    genre: e.genre,
                    country: e.country,
                }
            });

            if (combs.some(e => state[e.id] === undefined || !compareCombs(e, state[e.id]))) {
                const newCombs = {};
                for (const o of combs) {
                    newCombs[o.id] = o;
                }
                console.debug("Updating combs", newCombs);

                return {
                    ...state,
                    ...newCombs
                }
            }
            return state
        case 'REMOVE_COMB':
            const newState = {...state}
            delete newState[action.payload]
            return newState
        default:
            return state
    }
}

export function CombsProvider({children}) {
    const [combs, dispatch] = useReducer(reducer, {})

    return <CombsContext.Provider value={combs}>
        <CombsDispatchContext.Provider value={dispatch}>
            {children}
        </CombsDispatchContext.Provider>
    </CombsContext.Provider>
}

export function useCombs() {
    const combs = useContext(CombsContext);
    const getComb = (id, defaultValue = null) => {
        return combs[id] !== undefined ? combs[id] : defaultValue;
    }
    return {getComb, combs};
}

export function useCombsDispatch() {
    return useContext(CombsDispatchContext);
}

export function CombName({combId}) {
    const {getComb} = useCombs();
    const comb = getComb(combId, null);
    if (comb) {
        return <>{comb.fname} {comb.lname}</>
    } else {
        return <>[Comb #{combId}]</>
    }
}
