"use strict";
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 });
exports.ApiServerPack = void 0;
const antd_1 = require("antd");
const api_core_1 = require("./api-core");
const const_1 = require("@mometa/fs-handler/const");
const react_1 = __importDefault(require("react"));
const p_queue_1 = __importDefault(require("p-queue"));
const antd_2 = require("antd");
const code_editor_1 = require("../../../../shared/code-editor");
const open_react_element_1 = require("../../../../shared/open-react-element");
const utils_1 = require("../../utils/utils");
const getReactWrap = (anotherTo) => ({
    startStr: '<>',
    endStr: '</>',
    anotherTo
});
class ApiServerPack extends api_core_1.ApiCore {
    constructor(apiBaseURL = '') {
        super(apiBaseURL, {
            loading: (str) => antd_1.message.loading(str, 0),
            error: (str) => antd_1.message.error(str)
        });
        this.queue = new p_queue_1.default({ concurrency: 1 });
    }
    _submitOperation(requestData) {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.axios.post('/submit-op', requestData);
            return true;
        });
    }
    handleViewOp(opType, dom, extraData) {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.queue.pending && !this.closeTip) {
                this.closeTip = this.toast.loading('任务正在进行中，请等待');
            }
            try {
                return yield this.queue.add(() => {
                    if (this.queue.size === 0) {
                        if (this.closeTip) {
                            this.closeTip();
                            this.closeTip = null;
                        }
                    }
                    return this._handleViewOp(opType, dom, extraData);
                });
            }
            finally {
                if (this.queue.pending === 0 && this.queue.size === 0) {
                    if (this.closeTip) {
                        this.closeTip();
                        this.closeTip = null;
                    }
                }
            }
        });
    }
    confirmWhich(dom, opName, props) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            const data = dom.__mometa.getMometaData();
            let p;
            if ((_a = data.container) === null || _a === void 0 ? void 0 : _a.isFirstElement) {
                p = (0, open_react_element_1.openReactStandalone)((cb) => (react_1.default.createElement(antd_1.Modal, { visible: true, footer: react_1.default.createElement("div", null,
                        react_1.default.createElement(antd_1.Button, Object.assign({ type: 'primary', onClick: () => cb('container') }, props),
                            opName,
                            "\u5BB9\u5668"),
                        react_1.default.createElement(antd_1.Button, Object.assign({ type: 'primary', onClick: () => cb('self') }, props),
                            opName,
                            "\u81EA\u8EAB"),
                        react_1.default.createElement(antd_1.Button, { type: 'default', size: 'small', onClick: () => cb() }, "\u53D6\u6D88")) },
                    react_1.default.createElement(antd_1.Typography, null,
                        "\u68C0\u6D4B\u5230\u5143\u7D20\u5728\u5BB9\u5668\u5934\u90E8\uFF0C\u8BF7\u9009\u62E9\u5177\u4F53",
                        opName,
                        "\u54EA\u4E2A\uFF0C\u4EE3\u7801\u5982\u4E0B\uFF1A"),
                    react_1.default.createElement(antd_2.Form, { layout: 'vertical', style: { marginTop: 10 } },
                        react_1.default.createElement(antd_2.Form.Item, { label: '自身代码' },
                            react_1.default.createElement(code_editor_1.CodeEditor, { readOnly: true, value: data.text, height: '100px' })),
                        react_1.default.createElement(antd_2.Form.Item, { label: '容器代码' },
                            react_1.default.createElement(code_editor_1.CodeEditor, { readOnly: true, value: data.container.text, height: '200px' }))))));
            }
            else {
                p = new Promise((res) => {
                    antd_1.Modal.confirm({
                        title: `确认${opName}如下代码片段吗？`,
                        content: react_1.default.createElement(code_editor_1.CodeEditor, { readOnly: true, value: data.text, style: { marginTop: 10 } }),
                        okText: '确认',
                        cancelText: '取消',
                        okButtonProps: Object.assign({}, props),
                        onOk: () => res('self'),
                        onCancel: () => res(null)
                    });
                });
            }
            return yield p;
        });
    }
    _handleViewOp(opType, dom, extraData) {
        var _a, _b;
        return __awaiter(this, void 0, void 0, function* () {
            const data = dom.__mometa.getMometaData();
            let locationData = data;
            if ((_a = data.container) === null || _a === void 0 ? void 0 : _a.isFirstElement) {
                locationData = data.container;
            }
            switch (opType) {
                case 'move-dom': {
                    const { direction, toDom } = extraData;
                    const toData = toDom.__mometa.getMometaData();
                    const common = {
                        filename: data.filename,
                        relativeFilename: data.relativeFilename,
                        start: data.start,
                        end: data.end,
                        text: data.text
                    };
                    if (direction === 'up' || direction === 'down') {
                        return this.submitOperation({
                            type: const_1.OpType.MOVE_NODE,
                            preload: Object.assign(Object.assign({}, common), { data: {
                                    to: direction === 'up' ? toData.start : toData.end
                                } })
                        });
                    }
                    else if (direction === 'child') {
                        return this.submitOperation({
                            type: const_1.OpType.MOVE_NODE,
                            preload: Object.assign(Object.assign({}, common), { data: {
                                    to: toData.innerEnd
                                } })
                        });
                    }
                    break;
                }
                case 'insert-asset': {
                    const { asset, direction } = extraData;
                    if (direction === 'up' || direction === 'down') {
                        return this.submitOperation({
                            type: const_1.OpType.INSERT_NODE,
                            preload: {
                                filename: data.filename,
                                relativeFilename: data.relativeFilename,
                                to: direction === 'up' ? data.start : data.end,
                                data: {
                                    material: asset,
                                    wrap: data.isFirst ? getReactWrap(direction === 'down' ? data.start : data.end) : undefined
                                }
                            }
                        });
                    }
                    else if (direction === 'child') {
                        return this.submitOperation({
                            type: const_1.OpType.INSERT_NODE,
                            preload: {
                                relativeFilename: data.relativeFilename,
                                filename: data.filename,
                                to: data.innerEnd,
                                data: {
                                    material: asset
                                }
                            }
                        });
                    }
                    break;
                }
                case 'del': {
                    const result = yield this.confirmWhich(dom, '删除', { danger: true });
                    if (result === 'self') {
                        return this.submitOperation({
                            type: const_1.OpType.REPLACE_NODE,
                            preload: Object.assign(Object.assign({}, data), { data: {
                                    newText: data.isFirst ? 'null' : ''
                                } })
                        }, '删除');
                    }
                    else if (result === 'container') {
                        return this.submitOperation({
                            type: const_1.OpType.DEL,
                            preload: (0, utils_1.createPreload)(data, data.container)
                        });
                    }
                    break;
                }
                case 'up':
                case 'down': {
                    let to = opType === 'up' ? data.previousSibling.start : data.nextSibling.end;
                    return this.submitOperation({
                        type: const_1.OpType.MOVE_NODE,
                        preload: (0, utils_1.createPreload)(data, Object.assign(Object.assign({}, locationData), { 
                            // @ts-ignore
                            data: {
                                to
                            } }))
                    });
                }
                case 'copy': {
                    let result;
                    if ((_b = data.container) === null || _b === void 0 ? void 0 : _b.isFirstElement) {
                        result = yield this.confirmWhich(dom, '复制');
                    }
                    else {
                        result = 'self';
                    }
                    if (result === 'container') {
                        return this.submitOperation({
                            type: const_1.OpType.INSERT_NODE,
                            preload: (0, utils_1.createPreload)(data, {
                                to: locationData.end,
                                data: {
                                    newText: locationData.text
                                }
                            })
                        }, '复制');
                    }
                    else if (result === 'self') {
                        return this.submitOperation({
                            type: const_1.OpType.INSERT_NODE,
                            preload: (0, utils_1.createPreload)(data, {
                                to: data.end,
                                data: {
                                    newText: data.text,
                                    wrap: data.isFirst ? getReactWrap(data.start) : undefined
                                }
                            })
                        }, '复制');
                    }
                }
            }
        });
    }
}
exports.ApiServerPack = ApiServerPack;
function createApi(apiBaseURL) {
    return new ApiServerPack(apiBaseURL);
}
exports.default = createApi;
//# sourceMappingURL=create-api.js.map