import { createContext, useContext } from "react";

import type { Context } from "react";

type CustomControlContextProps<ValueType, ControlParameters> = {
    backboneView?: any;
    params?: {
        [key: string]: any;
        active: boolean;
        description: string;
        instanceNumber: number;
        label: string;
        priority: number;
        section: string;
        settings: {
            [key: string]: any;
            default?: any;
        };
        type: string;
        skipFieldSet?: boolean; // Optional boolean, set to `true` so the `ControlFieldset` control is not used at all
        className?: string; // Optional string
    } & ControlParameters;
    initializeNotifications?: (element: HTMLElement) => void;
    value?: ValueType;
    setValue?: (value: ValueType) => void;
};

/**
 * Create a side-effect-free context provider so custom controls can handle updates.
 */
class CustomControlContextFactory {
    private static context: Context<CustomControlContextProps<any, any>>;

    public static Context<ValueType, ControlParameters>(): Context<
        CustomControlContextProps<ValueType, ControlParameters>
    > {
        return (this.context =
            this.context || createContext<CustomControlContextProps<ValueType, ControlParameters>>({}));
    }
}

function useCustomControl<ValueType, ControlParameters>() {
    return useContext(CustomControlContextFactory.Context<ValueType, ControlParameters>());
}

export { CustomControlContextFactory, useCustomControl };
