import { create } from "zustand";

import { DialogDescription } from "../model/DialogProps";

type Store = {
	stack: DialogDescription[];
	push: (props: DialogDescription) => void;
	back: () => void;
	close: () => void;
	getIsRoot: () => boolean;
	getIsOpen: (key: string) => boolean;
};

export const useDialogStore = create<Store>((set, get) => ({
	stack: [],

	push: (props: DialogDescription) => {
		if (get().stack.some((x) => x.key === props.key)) {
			return;
		}

		set((state) => ({
			stack: [...state.stack, props],
		}));
	},

	back: () => {
		set((state) => {
			if (state.stack.length === 1) {
				return {
					stack: [],
				};
			}

			return {
				stack: state.stack.slice(0, -1),
			};
		});
	},

	close: () => {
		set(() => ({
			stack: [],
		}));
	},

	getIsRoot: () => get().stack.length === 1,
	getIsOpen: (key: string) => get().stack.some((x) => x.key === key),
}));
