import {useSetAtom} from "jotai/index";
import {PopupWindowCloseOptions, PopupWindowsState, TestablesPopupWindowsAtom} from "./atoms";
import {POPUP_CLOSE_ANIMATION_MS} from "../PopupWindow";

export const useOpenTestablesPopupWindow = () => {
    const setTestablesPopupWindows = useSetAtom(TestablesPopupWindowsAtom)

    return <ExtraData = any>(newWindow: PopupWindowsState<ExtraData>) => {
        setTestablesPopupWindows((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<PopupWindowsState['onClose']>[0], PopupWindowCloseOptions | undefined]
                        const removePopup = () => {
                            setTestablesPopupWindows((prevWindows) => [
                                ...prevWindows.filter((window) => {
                                    return window.context.id !== newWindow.context.id
                                })
                            ])
                        }

                        // call the event only on success
                        /*
                                                 if (status === 'success') {
                        */
                        if (!options?.skipCallback) {
                            newWindow.onClose(data)
                        }
                        /*
                                                 }
                        */
                        // close the popup
                        if (options?.deferWindowRemoval) {
                            window.setTimeout(removePopup, POPUP_CLOSE_ANIMATION_MS)
                        } else {
                            removePopup()
                        }
                    }
                }
            ]
        })
    }
}
