"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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 __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
exports.__esModule = true;
exports.getGitCodeLink = exports.ClickToSourceProviderStateless = void 0;
var react_1 = __importStar(require("react"));
var path_1 = __importDefault(require("path"));
var ClickToSourceContext = react_1.createContext({ provider: '' });
function ClickToSourceProviderStateless(_a) {
    var _b = _a.value, value = _b === void 0 ? { provider: '' } : _b, onChange = _a.onChange, _c = _a.linksConfig, linksConfig = _c === void 0 ? {} : _c, root = _a.root, _d = _a.className, className = _d === void 0 ? '' : _d, _e = _a.children, children = _e === void 0 ? null : _e, rest = __rest(_a, ["value", "onChange", "linksConfig", "root", "className", "children"]);
    // const [state, setState] = useState<ClickToSourceState>(value)
    var enabled = Boolean(value.provider);
    var ref = react_1.useRef();
    var disable = react_1.useCallback(function () {
        onChange(__assign(__assign({}, value), { provider: '' }));
    }, [onChange]);
    var onClickToSource = react_1.useCallback(function onClickToSource(e) {
        // e.preventDefault()
        e.stopPropagation();
        disable();
        var target = e.currentTarget;
        var filePath = target.getAttribute('data-vitro-filename');
        // TODO filename is a path realtive to the root of the repository, this path can be used on vscode or on github using different path.join
        var lineNumber = target.getAttribute('data-vitro-line');
        if (!filePath) {
            console.warn("no filename found among " + [target.attributes]
                .map(function (x) { return x.name + "='" + x.value + "'"; })
                .join(', '));
            return;
        }
        if (!lineNumber) {
            console.warn("no line number found for " + target + " among " + target.attributes);
            return;
        }
        openInNewTab(getGitCodeLink({
            provider: value.provider,
            filePath: filePath,
            lineNumber: lineNumber,
            linksConfig: linksConfig,
            root: root
        }));
    }, [value.provider]);
    react_1.useEffect(function () {
        var rootElem = ref.current;
        if (!rootElem) {
            console.error(new Error("no root ref"));
        }
        if (enabled) {
            var elements = Array.from(rootElem.querySelectorAll('.click-to-source-enabled *[data-vitro-filename]'));
            elements.forEach(function (elem) {
                elem.addEventListener('click', onClickToSource);
            });
        }
        else {
            var elements = Array.from(rootElem.querySelectorAll('*[data-vitro-filename]'));
            elements.forEach(function (elem) {
                elem.removeEventListener('click', onClickToSource);
            });
        }
    }, [enabled]);
    var enabledClassName = enabled ? 'click-to-source-enabled' : '';
    return (react_1["default"].createElement(ClickToSourceContext.Provider, { value: value },
        react_1["default"].createElement("div", __assign({ className: className
                ? className + " " + enabledClassName
                : enabledClassName, ref: ref }, rest), children)));
}
exports.ClickToSourceProviderStateless = ClickToSourceProviderStateless;
function getGitCodeLink(_a) {
    var provider = _a.provider, filePath = _a.filePath, root = _a.root, _b = _a.lineNumber, lineNumber = _b === void 0 ? 0 : _b, linksConfig = _a.linksConfig;
    var defaultBranch = 'master';
    if (provider == 'vscode') {
        return "vscode://file" + filePath + ":" + lineNumber;
    }
    else if (provider === 'github') {
        if (!linksConfig.github) {
            return '';
        }
        var relativePath = path_1["default"].relative(root, filePath);
        var _c = linksConfig.github, gitUrl = _c.url, branch = _c.branch, _d = _c.path, inPath = _d === void 0 ? defaultBranch : _d;
        var url = gitUrl + "/blob/" + branch + "/" + path_1["default"].join(inPath || '', relativePath || '');
        if (lineNumber) {
            url += "#L" + lineNumber;
        }
        return url;
    }
    else if (provider === 'gitlab') {
        if (!linksConfig.gitlab) {
            return '';
        }
        var relativePath = path_1["default"].relative(root, filePath);
        var _e = linksConfig.gitlab, gitUrl = _e.url, branch = _e.branch, _f = _e.path, inPath = _f === void 0 ? defaultBranch : _f;
        // https://gitlab.com/kmoshonskiy/moon/-/blob/master/.gitlab-ci.yml#L7
        var url = gitUrl + "/-/blob/" + branch + "/" + path_1["default"].join(inPath || '', relativePath || '');
        if (lineNumber) {
            url += "#L" + lineNumber;
        }
        return url;
    }
    throw new Error("Unknown click to source provider " + provider);
}
exports.getGitCodeLink = getGitCodeLink;
function openInNewTab(href) {
    console.info("Opening " + href);
    var aElem = document.createElement('a');
    Object.assign(aElem, {
        target: '_blank',
        href: href
    }).click();
    aElem.remove();
    // TODO remove a from DOM
}
//# sourceMappingURL=ClickToSource.js.map