import _asyncToGenerator from "@babel/runtime-corejs3/helpers/asyncToGenerator";
import _slicedToArray from "@babel/runtime-corejs3/helpers/slicedToArray";
import _regeneratorRuntime from "@babel/runtime-corejs3/regenerator";
import _findInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/find";
import _mapInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/map";
import _JSON$stringify from "@babel/runtime-corejs3/core-js-stable/json/stringify";
import React, { useCallback, useRef, useState } from "react";
import { documentTemplates, noop } from "../../utils";
import { getLogger } from "../../logger";
import { obfuscateField, updateHeight, updateTemplates } from "../frame/frame.actions";
import { HostConnector } from "../frame/HostConnector";
import { DomListener } from "../common/DomListener";
import { noAttachmentRenderer } from "./NoAttachmentRenderer";
import { jsx as ___EmotionJSX } from "@emotion/react";

var _getLogger = getLogger("FramedDocumentRenderer"),
    trace = _getLogger.trace;

export function FramedDocumentRenderer(_ref) {
  var templateRegistry = _ref.templateRegistry,
      _ref$attachmentToComp = _ref.attachmentToComponent,
      attachmentToComponent = _ref$attachmentToComp === void 0 ? noAttachmentRenderer : _ref$attachmentToComp;

  var _useState = useState(),
      _useState2 = _slicedToArray(_useState, 2),
      document = _useState2[0],
      setDocument = _useState2[1]; // used only to handle legacy setSelectTemplate function
  // dispatch function (below) is connected once through the frame and the reference to this function never change is
  // host and iframe. We need to use a reference to allow object mutation


  var documentForLegacyUsage = useRef();

  var _useState3 = useState(),
      _useState4 = _slicedToArray(_useState3, 2),
      rawDocument = _useState4[0],
      setRawDocument = _useState4[1];

  var _useState5 = useState(),
      _useState6 = _slicedToArray(_useState5, 2),
      templateName = _useState6[0],
      setTemplateName = _useState6[1];

  var toHost = useRef(noop);
  var templates = document ? documentTemplates(document, templateRegistry, attachmentToComponent) : [];
  var templateConfiguration = _findInstanceProperty(templates).call(templates, function (template) {
    return template.id === templateName;
  }) || templates[0] || {};
  var Template = templateConfiguration.template;
  var onConnected = useCallback(function (postMessage) {
    toHost.current = postMessage;
  }, []); // actions received by the parent hosting the component

  var dispatch = useCallback(function (action) {
    trace("in frame, received action", action.type);

    if (action.type === "RENDER_DOCUMENT") {
      setDocument(action.payload.document);
      documentForLegacyUsage.current = action.payload.document;

      if (action.payload.rawDocument) {
        setRawDocument(action.payload.rawDocument);
      }

      var run = /*#__PURE__*/function () {
        var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
          var _context;

          var templates;
          return _regeneratorRuntime.wrap(function _callee$(_context2) {
            while (1) {
              switch (_context2.prev = _context2.next) {
                case 0:
                  _context2.next = 2;
                  return _mapInstanceProperty(_context = documentTemplates(action.payload.document, templateRegistry, attachmentToComponent)).call(_context, function (template) {
                    return {
                      id: template.id,
                      label: template.label,
                      type: template.type
                    };
                  });

                case 2:
                  templates = _context2.sent;
                  toHost.current(updateTemplates(templates));

                case 4:
                case "end":
                  return _context2.stop();
              }
            }
          }, _callee);
        }));

        return function run() {
          return _ref2.apply(this, arguments);
        };
      }();

      run();
    } else if (action.type === "SELECT_TEMPLATE") {
      setTemplateName(action.payload);
    } else if (action.type === "GET_TEMPLATES") {
      var _context3;

      var _templates = _mapInstanceProperty(_context3 = documentTemplates(action.payload, templateRegistry, attachmentToComponent)).call(_context3, function (template) {
        return {
          id: template.id,
          label: template.label,
          type: template.type
        };
      });

      toHost.current(updateTemplates(_templates)); // send the result to the iframe

      return _templates; // react-native expect to get the result directly
    } else if (action.type === "PRINT") {
      window.print();
    } else {
      throw new Error("Action ".concat(_JSON$stringify(action), " is not handled"));
    }
  }, [templateRegistry, attachmentToComponent]);
  window.openAttestation = dispatch; // expose different actions for direct injection

  return ___EmotionJSX(DomListener, {
    onUpdate: function onUpdate(height) {
      return toHost.current(updateHeight(height));
    }
  }, ___EmotionJSX(HostConnector, {
    dispatch: dispatch,
    onConnected: onConnected
  }, document && Template && ___EmotionJSX("div", {
    className: "frameless-tabs",
    id: "rendered-certificate"
  }, ___EmotionJSX(Template, {
    document: document,
    wrappedDocument: rawDocument,
    handleObfuscation: function handleObfuscation(field) {
      return toHost.current(obfuscateField(field));
    }
  }))));
}
//# sourceMappingURL=FramedDocumentRenderer.js.map