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());
    });
};
import React from 'react';
import p from 'prefix-classname';
import zhCN from 'antd/lib/locale/zh_CN';
import { ConfigProvider, message } from 'antd';
import { CLS_PREFIX } from '../../config/const';
import Header, { useHeaderStatus } from '../components/header';
import Stage from '../components/stage';
import RightPanel from '../components/right-panel';
import LeftPanel from '../components/left-panel';
import { SharedProvider, useSharedProvider } from '@rcp/use.shared';
import { DoubleRightOutlined, DoubleLeftOutlined } from '@ant-design/icons';
import { Tooltip } from 'antd';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import './style.scss';
import createApi from '../components/stage/create-api';
import { createClientConnection } from './sse';
import { Button } from 'antd';
import { fetchPreload } from '../utils/fetch-preload';
import AppErrorBoundary from '../components/error-boundary';
import { handleErrors } from '../utils/error-overlay';
const cn = p('');
const c = p(`${CLS_PREFIX}`);
function CollapseBtn({ hide, dir, onClick }) {
    const title = hide ? '展开' : '收起';
    const style = {
        cursor: 'pointer',
        color: '#1890ff'
    };
    return (React.createElement("div", { onClick: onClick, className: c('__collapse', `-collapse-${dir}`, `-collapse-${hide ? 'hide' : 'show'}`) },
        React.createElement(Tooltip, { title: title },
            React.createElement(Button, { style: { padding: 0 }, size: 'small', shape: 'round', icon: (hide && dir === 'left') || (!hide && dir === 'right') ? (React.createElement(DoubleLeftOutlined, { style: style })) : (React.createElement(DoubleRightOutlined, { style: style })), type: 'link' }))));
}
const Body = ({ className, apiBaseURL, leftPanelProps, rightPanelProps, stageProps, bundlerURL }) => {
    const [mats, setMats] = React.useState([]);
    const [loading, setLoading] = React.useState(true);
    React.useEffect(() => {
        const conn = 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 = 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 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);
                message.error(err.message);
            }
        }));
        //
        return () => {
            conn.close();
            dispose === null || dispose === void 0 ? void 0 : dispose();
        };
    }, [apiBaseURL]);
    const api = React.useMemo(() => createApi(apiBaseURL), [apiBaseURL]);
    useSharedProvider(api, { key: 'api' });
    const [{ canSelect }] = useHeaderStatus();
    const [hideLeft, setHideLeft] = React.useState(false);
    const [hideRight, setHideRight] = React.useState(false);
    const hideChangedRef = React.useRef({ left: false, right: false });
    React.useEffect(() => {
        if (!hideChangedRef.current.left) {
            setHideLeft(!canSelect);
        }
        if (!hideChangedRef.current.right) {
            setHideRight(!canSelect);
        }
    }, [canSelect]);
    return (React.createElement("div", { className: cn(c(), className) },
        React.createElement(Header, { bundlerURL: bundlerURL }),
        React.createElement("div", { className: c('__main-content') },
            React.createElement("div", { className: c('__panel') },
                React.createElement(LeftPanel, Object.assign({}, leftPanelProps, { className: c('__l-panel', hideLeft && '-hide'), loading: loading, materials: mats })),
                React.createElement(CollapseBtn, { onClick: () => {
                        hideChangedRef.current.left = true;
                        setHideLeft((x) => !x);
                    }, hide: hideLeft, dir: 'left' })),
            React.createElement(Stage, Object.assign({ bundlerURL: bundlerURL }, stageProps, { className: c('__stage', hideLeft && `-stage-left-hide`, hideRight && '-stage-right-hide') })),
            React.createElement("div", { className: c('__panel') },
                React.createElement(RightPanel, Object.assign({}, rightPanelProps, { className: c('__r-panel', hideRight && '-hide') })),
                React.createElement(CollapseBtn, { onClick: () => {
                        hideChangedRef.current.right = true;
                        setHideRight((x) => !x);
                    }, hide: hideRight, dir: 'right' })))));
};
ConfigProvider.config({
    prefixCls: 'mmt-ant'
});
const Editor = React.memo((props) => {
    return (React.createElement(SharedProvider, null,
        React.createElement(ConfigProvider, { locale: zhCN, prefixCls: 'mmt-ant' },
            React.createElement(AppErrorBoundary, null,
                React.createElement(DndProvider, { backend: HTML5Backend },
                    React.createElement(Body, Object.assign({}, props)))))));
});
Editor.defaultProps = {
    apiBaseURL: 'http://localhost:8686/',
    bundlerURL: '/bundler.html'
};
export default Editor;
//# sourceMappingURL=index.js.map