"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = __importDefault(require("react"));
const prefix_classname_1 = __importDefault(require("prefix-classname"));
const zh_CN_1 = __importDefault(require("antd/lib/locale/zh_CN"));
const antd_1 = require("antd");
const const_1 = require("../../config/const");
const header_1 = __importStar(require("../components/header"));
const stage_1 = __importDefault(require("../components/stage"));
const right_panel_1 = __importDefault(require("../components/right-panel"));
const left_panel_1 = __importDefault(require("../components/left-panel"));
const use_shared_1 = require("@rcp/use.shared");
const icons_1 = require("@ant-design/icons");
const antd_2 = require("antd");
const react_dnd_1 = require("react-dnd");
const react_dnd_html5_backend_1 = require("react-dnd-html5-backend");
require("./style.scss");
const create_api_1 = __importDefault(require("../components/stage/create-api"));
const sse_1 = require("./sse");
const antd_3 = require("antd");
const fetch_preload_1 = require("../utils/fetch-preload");
const error_boundary_1 = __importDefault(require("../components/error-boundary"));
const error_overlay_1 = require("../utils/error-overlay");
const cn = (0, prefix_classname_1.default)('');
const c = (0, prefix_classname_1.default)(`${const_1.CLS_PREFIX}`);
function CollapseBtn({ hide, dir, onClick }) {
    const title = hide ? '展开' : '收起';
    const style = {
        cursor: 'pointer',
        color: '#1890ff'
    };
    return (react_1.default.createElement("div", { onClick: onClick, className: c('__collapse', `-collapse-${dir}`, `-collapse-${hide ? 'hide' : 'show'}`) },
        react_1.default.createElement(antd_2.Tooltip, { title: title },
            react_1.default.createElement(antd_3.Button, { style: { padding: 0 }, size: 'small', shape: 'round', icon: (hide && dir === 'left') || (!hide && dir === 'right') ? (react_1.default.createElement(icons_1.DoubleLeftOutlined, { style: style })) : (react_1.default.createElement(icons_1.DoubleRightOutlined, { style: style })), type: 'link' }))));
}
const Body = ({ className, apiBaseURL, leftPanelProps, rightPanelProps, stageProps, bundlerURL }) => {
    const [mats, setMats] = react_1.default.useState([]);
    const [loading, setLoading] = react_1.default.useState(true);
    react_1.default.useEffect(() => {
        const conn = (0, sse_1.createClientConnection)(apiBaseURL + 'sse');
        let dispose;
        let disposeError;
        function handleBuildProcess(fn) {
            return __awaiter(this, void 0, void 0, function* () {
                try {
                    yield fn();
                    disposeError === null || disposeError === void 0 ? void 0 : disposeError();
                    disposeError = null;
                }
                catch (err) {
                    disposeError = (0, error_overlay_1.handleErrors)([err]);
                }
            });
        }
        conn.addHandler((data) => __awaiter(void 0, void 0, void 0, function* () {
            var _a;
            try {
                switch (data.type) {
                    case 'set-materials': {
                        setMats((_a = data.data) !== null && _a !== void 0 ? _a : []);
                        setLoading(false);
                        break;
                    }
                    case 'materials-loading': {
                        setLoading(!!data.data);
                        break;
                    }
                    case 'set-materials-client-render': {
                        yield handleBuildProcess(() => __awaiter(void 0, void 0, void 0, function* () {
                            dispose === null || dispose === void 0 ? void 0 : dispose();
                            const { exported, dispose: _dis } = yield (0, fetch_preload_1.fetchPreload)(data.data);
                            dispose = _dis;
                            console.log('materials-client-render exports', exported);
                            setMats(exported !== null && exported !== void 0 ? exported : []);
                            setLoading(false);
                        }));
                        break;
                    }
                    case 'error': {
                        yield handleBuildProcess(() => {
                            throw new Error(data.data);
                        });
                    }
                }
            }
            catch (err) {
                console.error(err);
                antd_1.message.error(err.message);
            }
        }));
        //
        return () => {
            conn.close();
            dispose === null || dispose === void 0 ? void 0 : dispose();
        };
    }, [apiBaseURL]);
    const api = react_1.default.useMemo(() => (0, create_api_1.default)(apiBaseURL), [apiBaseURL]);
    (0, use_shared_1.useSharedProvider)(api, { key: 'api' });
    const [{ canSelect }] = (0, header_1.useHeaderStatus)();
    const [hideLeft, setHideLeft] = react_1.default.useState(false);
    const [hideRight, setHideRight] = react_1.default.useState(false);
    const hideChangedRef = react_1.default.useRef({ left: false, right: false });
    react_1.default.useEffect(() => {
        if (!hideChangedRef.current.left) {
            setHideLeft(!canSelect);
        }
        if (!hideChangedRef.current.right) {
            setHideRight(!canSelect);
        }
    }, [canSelect]);
    return (react_1.default.createElement("div", { className: cn(c(), className) },
        react_1.default.createElement(header_1.default, { bundlerURL: bundlerURL }),
        react_1.default.createElement("div", { className: c('__main-content') },
            react_1.default.createElement("div", { className: c('__panel') },
                react_1.default.createElement(left_panel_1.default, Object.assign({}, leftPanelProps, { className: c('__l-panel', hideLeft && '-hide'), loading: loading, materials: mats })),
                react_1.default.createElement(CollapseBtn, { onClick: () => {
                        hideChangedRef.current.left = true;
                        setHideLeft((x) => !x);
                    }, hide: hideLeft, dir: 'left' })),
            react_1.default.createElement(stage_1.default, Object.assign({ bundlerURL: bundlerURL }, stageProps, { className: c('__stage', hideLeft && `-stage-left-hide`, hideRight && '-stage-right-hide') })),
            react_1.default.createElement("div", { className: c('__panel') },
                react_1.default.createElement(right_panel_1.default, Object.assign({}, rightPanelProps, { className: c('__r-panel', hideRight && '-hide') })),
                react_1.default.createElement(CollapseBtn, { onClick: () => {
                        hideChangedRef.current.right = true;
                        setHideRight((x) => !x);
                    }, hide: hideRight, dir: 'right' })))));
};
antd_1.ConfigProvider.config({
    prefixCls: 'mmt-ant'
});
const Editor = react_1.default.memo((props) => {
    return (react_1.default.createElement(use_shared_1.SharedProvider, null,
        react_1.default.createElement(antd_1.ConfigProvider, { locale: zh_CN_1.default, prefixCls: 'mmt-ant' },
            react_1.default.createElement(error_boundary_1.default, null,
                react_1.default.createElement(react_dnd_1.DndProvider, { backend: react_dnd_html5_backend_1.HTML5Backend },
                    react_1.default.createElement(Body, Object.assign({}, props)))))));
});
Editor.defaultProps = {
    apiBaseURL: 'http://localhost:8686/',
    bundlerURL: '/bundler.html'
};
exports.default = Editor;
//# sourceMappingURL=index.js.map