import {create} from "zustand";
import {persist} from "zustand/middleware";

interface AnswerStore {
    listAnswer: any;
    updateAnswerList: (id: number, index: number, values: unknown) => void;
    removeAnswer: any;
    createAnswer: (idQuiz: number, idQuestion: number) => void;
}

export const answerStore = create<AnswerStore>()(

    persist(
        (set, get) => ({
            listAnswer: {
                2537998: {
                    3677473: {
                        variants:
                            [
                                ""
                            ],
                        own: true,
                        multi: true
                    }
                }
            },
            updateAnswerList: (id: number, index: number, values: any) => {
                const array = get()["listAnswer"][id] || [];
                array[index] = {
                    ...array[index],
                    ...values
                };
                const state = get()["listAnswer"] || {};
                state[id] = array
                set({listAnswer: state});
            },

            createAnswer:(idQuiz: number, idQuestion: number) => {
                const array = get()["listAnswer"][idQuiz][idQuestion] || [];
                array.push(
                    {
                        variants:
                            [
                            ""
                            ],
                        own: true,
                        multi: true
                    }
                )
                const state = get()["listAnswer"] || {};
                state[idQuiz][idQuestion] = array
                set({listAnswer: state});
            },

            removeAnswer: (id:number, index: number) => {
                const array = get()["listAnswer"][id] || [];
                array.splice(index, 1)
                const state = get()["listAnswer"] || {};
                state[id] = array
                set({listAnswer: state});
            },
        }),

        {
            name: "answer",
        }
    )
);