/*
 * Copyright 2021 The Kubernetes Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
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 { isAbsolute as pathIsAbsolute, dirname, join, relative } from 'path';
import { maybeKuiLink, pexecInCurrentTab } from '@kui-shell/core';
import { anchorFrom } from './heading';
import { activateTab } from './tabbed';
function isUrl(a) {
    return /^https?:/.test(a);
}
function isAbsolute(uri) {
    return isUrl(uri) || pathIsAbsolute(uri);
}
const Tooltip = React.lazy(() => import('../../../spi/Tooltip'));
export default function a(mdprops, uuid, repl) {
    return function a(props) {
        const isKuiCommand = props.href.startsWith('#kuiexec?command=');
        const isLocal = !/^http/i.test(props.href);
        const isNotebook = /\.md$/.test(props.href);
        const target = !isLocal && !isNotebook ? '_blank' : undefined;
        const onClick = !isLocal && !isKuiCommand && !isNotebook
            ? (evt) => evt.stopPropagation()
            : (evt) => __awaiter(this, void 0, void 0, function* () {
                evt.stopPropagation();
                let file = props.href;
                if (isKuiCommand) {
                    const raw = props.href.match(/#kuiexec\?command=([^&]+)(&quiet)?/);
                    if (raw) {
                        const cmdline = decodeURI(raw[1]);
                        const echo = !raw[2];
                        if (repl) {
                            return repl.pexec(cmdline, { echo });
                        }
                        else {
                            pexecInCurrentTab(cmdline, undefined, !echo);
                        }
                    }
                }
                else if (props.href.charAt(0) === '#') {
                    // in case this is a reference to a section in the current kui tab
                    // TODO: reference to a section in a different kui tab?
                    const tab = mdprops.tab;
                    if (tab) {
                        tab.show(`[data-markdown-anchor="${anchorFrom(uuid, props.href.slice(1))}"]`);
                    }
                    // in case this is a reference to a markdown tab in this kui tab
                    activateTab(props.href.slice(1), evt);
                }
                else if (file) {
                    if ((isLocal || isNotebook) && !isAbsolute(file)) {
                        // e.g. if a markdown has a relative reference to
                        // another in the same directory -- not the same as
                        // the user's CWD! the same as the directory of that
                        // first markdown
                        const baseUrl = mdprops.baseUrl || (mdprops.fullpath ? join(dirname(mdprops.fullpath), '{filename}') : undefined);
                        if (baseUrl) {
                            const absoluteHref = baseUrl.replace('{filename}', props.href);
                            if (!isNotebook) {
                                const relativeToCWD = relative(process.cwd() || process.env.PWD, absoluteHref);
                                file = relativeToCWD;
                            }
                            else if (/^https?:/.test(absoluteHref)) {
                                // reference to http://
                                file = absoluteHref.replace(/\.\//g, '');
                            }
                            else {
                                file = absoluteHref;
                            }
                        }
                    }
                    const cmd = isNotebook ? 'replay' : 'open';
                    const exec = isNotebook ? 'qexec' : 'pexec';
                    return repl[exec](`${cmd} ${repl.encodeComponent(file)}`);
                }
            });
        if (!props.href) {
            return React.createElement("a", { className: mdprops.className }, props.children);
        }
        else if (!isLocal && mdprops.noExternalLinks) {
            return React.createElement("span", { className: mdprops.className }, props.href);
        }
        else {
            const isKuiBlockLink = props.href.startsWith('#kui-link-');
            const tip = isKuiCommand
                ? `### Command Execution\n#### ${decodeURI(props.href.slice(props.href.indexOf('=') + 1)).replace('&quiet', '')}\n\n\`Link will execute a command\``
                : isKuiBlockLink
                    ? `### Block Link\n\n\`Link will scroll the block into view\``
                    : props.href.charAt(0) === '#'
                        ? `### In-Page Link\n#### ${props.href}\n\n\`Element will scroll into view\``
                        : isNotebook
                            ? `### Notebook\n#### ${props.href.replace(/^\.\//, '')}\n\n\`The linked notebook will open in a separate tab\``
                            : isLocal
                                ? `### File Link\n#### ${props.href}\n\n\`The linked file will open in this tab\``
                                : `### External Link\n#### ${props.href}\n\n\`Link will open in a separate window\``;
            const kuiLink = maybeKuiLink(props.href);
            const href = isKuiCommand || isNotebook
                ? '#'
                : !isKuiBlockLink && mdprops.baseUrl && !isAbsolute(props.href)
                    ? mdprops.baseUrl.replace('{filename}', props.href.replace(/^\s*\.\//g, ''))
                    : props.href;
            return (React.createElement(Tooltip, { markdown: tip },
                React.createElement("a", { title: props.title, href: href, target: target, onClick: onClick, className: kuiLink ? 'kui--link-status' : '' }, props.children)));
        }
    };
}
//# sourceMappingURL=a.js.map