import {
    useEffect,
    Fragment
} from "react";
import type {
    ICoreComplexProviderProps,
    ICoreComplexContext
} from "./type";
import "./cryptoPolyfill";
import {
    CoreComplexClient
} from "core-complex-client";
import NCoreContext, {
    type ConfigType
} from "ncore-context";

class NCoreUIKitCoreComplex extends NCoreContext<ICoreComplexContext, ConfigType<ICoreComplexContext>> {
    constructor() {
        super({
            client: null
        }, {
            key: "NCoreUIKit-CoreComplexContext"
        });
    }

    Render = ({
        privateKeyID,
        rsaPublicKey,
        privateKey,
        children,
        appID
    }: ICoreComplexProviderProps) => {
        useEffect(() => {
            if(!this.state.client) {
                this.setState({
                    client: new CoreComplexClient({
                        privateKeyID,
                        rsaPublicKey,
                        privateKey,
                        appID
                    })
                });
            }
        }, [
            privateKeyID,
            rsaPublicKey,
            privateKey,
            appID
        ]);

        return <Fragment>
            {children}
        </Fragment>;
    };
}

const ncoreUIKitCoreComplex = new NCoreUIKitCoreComplex();

export const useContext = ncoreUIKitCoreComplex.useContext;

const CoreComplexProvider = (props: ICoreComplexProviderProps) => {
    const Provider = ncoreUIKitCoreComplex.Provider;
    const Render = ncoreUIKitCoreComplex.Render;

    return <Provider>
        <Render
            privateKeyID={props.privateKeyID}
            rsaPublicKey={props.rsaPublicKey}
            privateKey={props.privateKey}
            appID={props.appID}
        >
            {props.children}
        </Render>
    </Provider>;
};
export default CoreComplexProvider;
