import {useReducer} from "react";
import {DPassGateCreateForm} from "../../../models/DPass/NewInvitation";

interface Action {
    type: 'array' | 'property'
    property?: string
    index?: number
    value?: any
}

const useDpassGateForm = (FormInit:DPassGateCreateForm) => {
    function reducer(state: DPassGateCreateForm, action: Action) {

        const {type, property, value, index = -1} = action

        //DEEP COPY PREVIOUS STATE
        // const newState: DPassGateCreateForm = JSON.parse(JSON.stringify(state));
        const newState: DPassGateCreateForm =  {...state};

        switch (type) {

            case "array":

                // @ts-ignore
                newState[property][index] = value
                break;

            case 'property':
                // @ts-ignore
                newState[property] = value
                break;
        }


        return newState
    }

    const [formData, dispatch] = useReducer(reducer, FormInit);

    return [formData, dispatch] as const


}

export default useDpassGateForm