"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = __importStar(require("react"));
const react_redux_1 = require("react-redux");
const react_router_dom_1 = require("react-router-dom");
const antd_1 = require("antd");
const styled_components_1 = __importDefault(require("styled-components"));
const ACTIONS = __importStar(require("@/actions/builder/events"));
const main_1 = require("@/actions/builder/main");
const index_1 = require("@/constants/index");
const utils_1 = require("@/sagas/builder/utils");
const global_1 = require("@/utils/global");
const events_1 = require("./events");
const Content = styled_components_1.default.div `
  height: 100%;
  background: #f2f2f2;
`;
const mapStateToProps = (store) => ({
    components: store.builder.component.components,
    application: store.builder.main.application,
    selectedNode: store.builder.main.selectedNode,
    state: store.builder.main.formattedData,
    mock: store.builder.main.mock,
    pageLocale: store.builder.header.locale,
    file: store.builder.main.file,
    pageNode: store.builder.main.pageNode,
});
const mapDispatchToProps = {
    selectComponent: main_1.selectComponent,
    updateComponent: ACTIONS.updateComponent,
    removeComponent: ACTIONS.removeComponent,
    copyComponent: ACTIONS.copyComponent,
    dropComponent: ACTIONS.dropComponent,
};
const Viewer = (props) => {
    var _a;
    const [frameLoaded, setFrameLoaded] = (0, react_1.useState)(false);
    const { loading, state, components = [], application, mock, file, pageNode, pageLocale, selectedNode, selectComponent, updateComponent, removeComponent, copyComponent, dropComponent, changeWindow, } = props;
    const { host = [], slug = '' } = application;
    const { formattedSchemas: structure } = state;
    const locale = (0, global_1.getGlobalLocale)() || 'en';
    const history = (0, react_router_dom_1.useHistory)();
    const isPage = file.type === 'page';
    // @ts-ignore
    const previewHtmlURL = __DEV__
        ? 'http://localhost:3003'
        : host[0] && slug
            ? `${(_a = host[0]) === null || _a === void 0 ? void 0 : _a.url}/${slug}${index_1.EDITOR_PATH}`
            : '';
    const handleLinkChange = (target, _opt) => {
        history.push(target);
    };
    const handleFrameLoaded = (_opt) => {
        setFrameLoaded(true);
    };
    // listeners handlers
    const handlers = {
        onSelectComponent: selectComponent,
        onUpdateComponent: updateComponent,
        onRemoveComponent: removeComponent,
        onCopyComponent: copyComponent,
        onDropComponent: dropComponent,
        onWindowChange: changeWindow,
        onLinkChange: handleLinkChange,
        onFrameLoaded: handleFrameLoaded,
    };
    const onListeners = (event) => {
        events_1.listeners.listener(event, handlers);
    };
    (0, react_1.useEffect)(() => {
        window.addEventListener('message', onListeners, false);
        return () => {
            window.removeEventListener('message', onListeners);
        };
    }, []);
    (0, react_1.useEffect)(() => {
        var _a;
        if (events_1.posters.handleInit && application.id && structure) {
            const sysConfig = {
                locale,
                mockable: !!(mock === null || mock === void 0 ? void 0 : mock.enable),
                // @ts-ignore
                visualFrameSrc: __DEV__ ? '/environment.html' : slug ? `/${slug}${index_1.EDITOR_ENV_PATH}` : '',
            };
            const pageConfig = {
                locale: pageLocale,
            };
            // get select node
            let selectNode = null;
            if (selectedNode) {
                selectNode = (0, utils_1.findStructureById)(structure, selectedNode.id);
                if (!selectNode) {
                    selectNode = (0, utils_1.findStructureByExtendId)(structure, selectedNode.id);
                }
                // TODO: style logic, need to general
                if (selectNode) {
                    const { children = [] } = selectNode;
                    const isStyleContainer = children.length === 1 && selectNode.name === index_1.STYLE_CONTAINER;
                    if (isStyleContainer) {
                        selectNode = children[0];
                    }
                }
            }
            // root node
            const rootNode = pageNode
                ? Object.assign(Object.assign({}, pageNode), { __editorConfig: {
                        templateBind: isPage,
                        disableTemplateBind: isPage && !!((_a = pageNode.extension) === null || _a === void 0 ? void 0 : _a.extendId),
                    } })
                : null;
            events_1.posters.handleInit({
                components,
                structure,
                selectNode: selectNode,
                rootNode,
                config: {
                    sys: sysConfig,
                    app: {
                        appId: application.id,
                    },
                    page: pageConfig,
                },
            });
        }
    }, [frameLoaded, structure, components, pageLocale, application.id]);
    return (react_1.default.createElement(antd_1.Spin, { spinning: loading || !frameLoaded }, structure ? (react_1.default.createElement(Content, null,
        react_1.default.createElement("iframe", { title: "main-view", name: "main-view", id: "main-view", src: previewHtmlURL, frameBorder: "0", scrolling: "yes", width: "100%", height: "100%", style: { display: 'block', visibility: 'visible' }, onLoad: handleFrameLoaded }))) : null));
};
exports.default = (0, react_redux_1.connect)(mapStateToProps, mapDispatchToProps)(Viewer);
