import React, { useEffect, useRef } from "react";
import { useChildFrame } from "./useFrame";
/**
 * Component creating a frame and establishing a connection with it.
 * Once the connection has been established, `onConnected` will be called and will provide, as first parameter, a function to send actions to the frame.
 * This component must be provided
 * - a `dispatch `function that will listen for actions coming from the frame
 * - the URL of the decentralized renderer to use as the `source` prop
 */
export var FrameConnector = function (_a) {
    var dispatch = _a.dispatch, methods = _a.methods, source = _a.source, onConnected = _a.onConnected, style = _a.style, _b = _a.className, className = _b === void 0 ? "" : _b;
    var iframe = useRef(null);
    // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
    // @ts-ignore error because of typescript distributivity
    // FrameConnectorProps can me mapped to UseLegacyChildrenFrameProps which is not correct. It could be solved using
    // conditional but there is a hooks rules saying shouldn't use conditional
    var _c = useChildFrame({ methods: methods, dispatch: dispatch, iframe: iframe }), connected = _c[0], toFrame = _c[1];
    useEffect(function () {
        if (connected) {
            onConnected(Object.assign(function (action) {
                if (toFrame.dispatch) {
                    toFrame.dispatch(action);
                }
            }, {
                renderDocument: function (document, rawDocument) {
                    if (toFrame.renderDocument) {
                        toFrame.renderDocument(document, rawDocument);
                    }
                },
                selectTemplateTab: function (tabIndex) {
                    if (toFrame.selectTemplateTab) {
                        toFrame.selectTemplateTab(tabIndex);
                    }
                },
                print: function () {
                    if (toFrame.print) {
                        toFrame.print();
                        return true;
                    }
                    return false;
                }
            }));
        }
    }, [connected, toFrame, onConnected]);
    return (React.createElement("iframe", { title: "Decentralised Rendered Certificate", id: "iframe", ref: iframe, src: source, style: style, className: className }));
};
//# sourceMappingURL=FrameConnector.js.map