"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WalkthroughsEditorView = void 0;
const tslib_1 = require("tslib");
const classnames_1 = tslib_1.__importDefault(require("classnames"));
const react_1 = tslib_1.__importStar(require("react"));
const ide_components_1 = require("@opensumi/ide-components");
const ide_core_browser_1 = require("@opensumi/ide-core-browser");
const ide_markdown_1 = require("@opensumi/ide-markdown");
const ide_theme_1 = require("@opensumi/ide-theme");
const common_1 = require("../../common");
const walkthroughs_service_1 = require("../walkthroughs.service");
const walkthroughs_view_module_less_1 = tslib_1.__importDefault(require("./walkthroughs-view.module.less"));
const WalkthroughsEditorView = ({ resource: { uri } }) => {
    const walkthroughsService = (0, ide_core_browser_1.useInjectable)(walkthroughs_service_1.WalkthroughsService);
    const contextKeyService = (0, ide_core_browser_1.useInjectable)(ide_core_browser_1.IContextKeyService);
    const { query: id, authority: extensionId } = uri;
    const [walkthrough, setWalkthrough] = (0, react_1.useState)();
    const [currentStepId, setCurrentStepId] = (0, react_1.useState)();
    (0, react_1.useEffect)(() => {
        if (walkthrough && walkthrough.steps.length > 0) {
            // 默认选第一个 step
            if (!currentStepId) {
                setCurrentStepId(walkthrough.steps[0].id);
            }
        }
    }, [walkthrough, currentStepId]);
    (0, react_1.useEffect)(() => {
        if (id) {
            setWalkthrough(walkthroughsService.getWalkthrough(id));
        }
    }, [id, walkthrough]);
    const getCurrentStep = (0, react_1.useCallback)(() => { var _a; return walkthrough && ((_a = walkthrough.steps.find((s) => s.id === currentStepId)) === null || _a === void 0 ? void 0 : _a.media); }, [currentStepId, walkthrough]);
    return (react_1.default.createElement("div", { className: walkthroughs_view_module_less_1.default.getting_started_container },
        react_1.default.createElement("div", { className: walkthroughs_view_module_less_1.default.getting_started_detailsContent },
            react_1.default.createElement("div", { className: walkthroughs_view_module_less_1.default.category_container },
                react_1.default.createElement("div", { className: walkthroughs_view_module_less_1.default.category_icon }, walkthrough && walkthrough.icon.type === 'image' && react_1.default.createElement("img", { src: walkthrough.icon.path })),
                react_1.default.createElement("div", { className: walkthroughs_view_module_less_1.default.category_description_container },
                    react_1.default.createElement("h2", { className: walkthroughs_view_module_less_1.default.category_title }, walkthrough === null || walkthrough === void 0 ? void 0 : walkthrough.title),
                    react_1.default.createElement("div", { className: walkthroughs_view_module_less_1.default.category_description }, walkthrough === null || walkthrough === void 0 ? void 0 : walkthrough.description))),
            react_1.default.createElement("div", { className: walkthroughs_view_module_less_1.default.steps_container },
                react_1.default.createElement("div", { className: walkthroughs_view_module_less_1.default.getting_started_detail_container },
                    react_1.default.createElement("div", { className: walkthroughs_view_module_less_1.default.step_list_container }, walkthrough
                        ? walkthrough.steps
                            .filter((s) => contextKeyService.match(s.when))
                            .map((s) => (react_1.default.createElement(StepItem, { key: s.id, step: s, isExpanded: s.id === currentStepId, onSelected: setCurrentStepId })))
                        : null))),
            react_1.default.createElement("div", { className: walkthroughs_view_module_less_1.default.getting_started_media }, currentStepId && (react_1.default.createElement(MediaContainer, { media: getCurrentStep(), extensionId: extensionId, stepId: currentStepId }))))));
};
exports.WalkthroughsEditorView = WalkthroughsEditorView;
const StepItem = ({ step, isExpanded, onSelected, }) => {
    const openerService = (0, ide_core_browser_1.useInjectable)(ide_core_browser_1.IOpenerService);
    const walkthroughsService = (0, ide_core_browser_1.useInjectable)(walkthroughs_service_1.WalkthroughsService);
    const iconService = (0, ide_core_browser_1.useInjectable)(ide_theme_1.IIconService);
    const [isCheck, setIsCheck] = (0, react_1.useState)(false);
    const { description } = step;
    (0, react_1.useEffect)(() => {
        const disposable = walkthroughsService.onDidProgressStep((event) => {
            const { id, done } = event;
            if (id === step.id) {
                if (done) {
                    setIsCheck(done);
                }
            }
        });
        return () => disposable.dispose();
    }, []);
    const handleCheckboxChange = (0, react_1.useCallback)(() => {
        setIsCheck(!isCheck);
        walkthroughsService.progressByEvent(common_1.CompletionEventsType.stepSelected + ':' + step.id);
    }, [isCheck, step.id]);
    const handleOpen = (0, react_1.useCallback)((node) => {
        const { href } = node;
        openerService.open(href);
        if (/^http(s)?:\/\//.test(href)) {
            walkthroughsService.progressByEvent(common_1.CompletionEventsType.onLink + ':' + href);
        }
    }, []);
    const getDescriptionComplexElements = (0, react_1.useCallback)(() => {
        if (description.length === 0) {
            return null;
        }
        const lineElements = [];
        description.map((desc, i) => {
            if (desc.nodes.length === 1 && typeof desc.nodes[0] !== 'string') {
                const node = desc.nodes[0];
                lineElements.push(react_1.default.createElement("div", { key: i.toString() + lineElements.length, title: node.title },
                    react_1.default.createElement(ide_components_1.Button, { onClick: () => handleOpen(node) }, (0, ide_core_browser_1.transformLabelWithCodicon)(node.label, {}, iconService.fromString.bind(iconService)))));
            }
            else {
                const textNodes = desc.nodes.map((node, idx) => {
                    if (typeof node === 'string') {
                        return node;
                    }
                    else {
                        return (react_1.default.createElement("a", { key: node.label + '#' + idx, title: node.title, onClick: () => handleOpen(node) }, node.label));
                    }
                });
                lineElements.push(react_1.default.createElement("p", { key: i.toString() + lineElements.length.toString() + textNodes.length.toString() }, textNodes));
            }
        });
        return (react_1.default.createElement("div", { className: walkthroughs_view_module_less_1.default.step_description_container },
            react_1.default.createElement(react_1.default.Fragment, null, lineElements)));
    }, [description]);
    const renderLabel = (0, react_1.useCallback)(() => (0, ide_core_browser_1.transformLabelWithCodicon)(step.title, {}, iconService.fromString.bind(iconService)), [step.title]);
    return (react_1.default.createElement("div", { className: (0, classnames_1.default)(walkthroughs_view_module_less_1.default.getting_started_step, isExpanded && walkthroughs_view_module_less_1.default.expanded), onClick: () => onSelected(step.id) },
        react_1.default.createElement("div", { className: walkthroughs_view_module_less_1.default.checkbox },
            react_1.default.createElement(ide_components_1.CheckBox, { id: step.id, onChange: handleCheckboxChange, checked: isCheck })),
        react_1.default.createElement("div", { className: walkthroughs_view_module_less_1.default.step_container },
            react_1.default.createElement("h3", { className: walkthroughs_view_module_less_1.default.step_title }, renderLabel()),
            isExpanded && getDescriptionComplexElements())));
};
/**
 * media 有 img、svg、markdown 三种格式
 */
const MediaContainer = ({ media, extensionId, stepId }) => {
    const themeService = (0, ide_core_browser_1.useInjectable)(ide_theme_1.IThemeService);
    const walkthroughsService = (0, ide_core_browser_1.useInjectable)(walkthroughs_service_1.WalkthroughsService);
    const [svgContent, setSvgContent] = (0, react_1.useState)('');
    const [markdownContent, setMarkdownContent] = (0, react_1.useState)('');
    const readFileContent = (0, react_1.useCallback)(async (path) => {
        if ((media === null || media === void 0 ? void 0 : media.type) === 'image') {
            return '';
        }
        if (path) {
            const content = await walkthroughsService.getFileContent(extensionId, path);
            return content.toString();
        }
        return '';
    }, [media]);
    (0, react_1.useEffect)(() => {
        const rawStep = walkthroughsService.getStepsByExtension(stepId);
        if (!rawStep) {
            return;
        }
        if (media && media.type === 'svg' && rawStep.media.svg) {
            readFileContent(rawStep.media.svg).then(setSvgContent);
        }
        if (media && media.type === 'markdown' && rawStep.media.markdown) {
            readFileContent(rawStep.media.markdown).then(setMarkdownContent);
        }
    }, [media, stepId]);
    if (!media) {
        return null;
    }
    if (media.type === 'image') {
        const themeType = themeService.getCurrentThemeSync().type;
        const src = media.path[themeType].toString(true).replace(/ /g, '%20');
        return (react_1.default.createElement(react_1.default.Fragment, null,
            react_1.default.createElement("img", { alt: media.altText, srcSet: src.toLowerCase().endsWith('.svg') ? src : src + ' 1.5x' })));
    }
    // 由于 svg 标签里可能存在 command: 的 href link，所以需要直接读取文件渲染 svg 标签，然后拦截点击事件给 openservice
    if (media.type === 'svg') {
        return (react_1.default.createElement(react_1.default.Fragment, null,
            react_1.default.createElement("div", { className: walkthroughs_view_module_less_1.default.media_svg_container, dangerouslySetInnerHTML: { __html: svgContent } })));
    }
    if (media.type === 'markdown') {
        return (react_1.default.createElement(react_1.default.Fragment, null,
            react_1.default.createElement(MarkdownMedia, { content: markdownContent, media: media })));
    }
    return null;
};
const MarkdownMedia = ({ content, media }) => {
    const openerService = (0, ide_core_browser_1.useInjectable)(ide_core_browser_1.IOpenerService);
    if (media.type !== 'markdown') {
        return null;
    }
    const relativePath = (0, react_1.useCallback)(() => media.base.resolve('/').toString(), [media, content]);
    return (react_1.default.createElement(ide_markdown_1.Markdown, { content: content, options: { baseUrl: relativePath() }, onLinkClick: (uri) => openerService.open(uri) }));
};
//# sourceMappingURL=walkthroughs-view.js.map