import {useSetAtom} from "jotai/index";
import {SelectMenuPopupWindowCloseOptions, SelectMenuPopupWindowsAtom, SelectMenuPopupWindowState} from "./atoms";
import {POPUP_CLOSE_ANIMATION_MS} from "../PopupWindow";

export const useOpenSelectMenuPopupWindow = () => {
    const setSelectMenuPopupWindows = useSetAtom(SelectMenuPopupWindowsAtom)

    return (newWindow: SelectMenuPopupWindowState) => {
        setSelectMenuPopupWindows((prev) => {
            if (prev.find((window) => window.context.id === newWindow.context.id)) {
                // if the window already exists, just return the previous state
                return prev;
            }
            return [
                ...prev,
                {
                    ...newWindow,
                    onClose: (...parameters) => {
                        const [data, options = {}] = parameters as [Parameters<SelectMenuPopupWindowState['onClose']>[0], SelectMenuPopupWindowCloseOptions | undefined]
                        const removePopup = () => {
                            setSelectMenuPopupWindows((prevWindows) => [
                                ...prevWindows.filter((window) => {
                                    return window.context.id !== newWindow.context.id
                                })
                            ])
                        }

                        if (!options?.skipCallback) {
                            newWindow.onClose(data)
                        }

                        // close the popup
                        if (options?.deferWindowRemoval) {
                            window.setTimeout(removePopup, POPUP_CLOSE_ANIMATION_MS)
                        } else {
                            removePopup()
                        }
                    }
                }
            ]
        })
    }
}
