"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
var axios_1 = require("axios");
var path = require("path");
var fs = require("fs-extra");
var tar = require("tar");
var showdown = require("showdown");
var emoji = require("node-emoji");
var fileLister_1 = require("./fileLister");
var os = require("os");
var config_service_js_1 = require("./config-service.js");
var instance;
var ArtifactoryService = /** @class */ (function () {
    function ArtifactoryService() {
        var _this = this;
        if (instance) {
            return instance;
        }
        this.tmpDir = path.join(os.homedir(), '.npmfrog', 'package-cache');
        this.packageDetailCache = {};
        process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
        config_service_js_1.default
            .getConfig()
            .then(function (config) {
            var repoKey = config.artifactory.repoKey;
            var s = config.artifactory.https ? 's' : '';
            axios_1.default.defaults.baseURL = _this.baseURL = "http" + s + "://" + config.artifactory.host + "/artifactory/api/npm/" + repoKey;
            axios_1.default.defaults.headers.common.Authorization = config.artifactory.apiKey;
        })
            .catch(function (error) {
            console.error(error);
        });
        instance = this;
    }
    ArtifactoryService.prototype.fetchPackages = function () {
        var _this = this;
        if (process.env.MOCK) {
            return new Promise(function (resolve, reject) {
                resolve(_this.createAxiosResponse(fs.readJSONSync(path.join(__dirname, 'mock', 'packages-all.json'))));
            });
        }
        return axios_1.default
            .get("/-/all")
            .then(function (response) {
            return response;
        })
            .catch(function (error) {
            return new Promise(function (resolve, reject) {
                resolve(_this.createAxiosResponse(_this.packageDetailCache));
            });
        });
    };
    ArtifactoryService.prototype.getPackageDetail = function (_a) {
        var scope = _a.scope, packageName = _a.packageName, version = _a.version;
        return __awaiter(this, void 0, void 0, function () {
            var latestVersionResponse, currentVersion, key, packageDetailResponse, _b, _c, additionalCode, _d;
            var _this = this;
            return __generator(this, function (_e) {
                switch (_e.label) {
                    case 0: return [4 /*yield*/, this.getDistTags({ scope: scope, packageName: packageName })];
                    case 1:
                        latestVersionResponse = _e.sent();
                        currentVersion = version || latestVersionResponse.data.latest;
                        key = scope + "-" + packageName;
                        if (!process.env.MOCK) return [3 /*break*/, 3];
                        return [4 /*yield*/, new Promise(function (resolve, reject) {
                                var packageResource = path.join(__dirname, 'mock', packageName + ".json");
                                var data;
                                try {
                                    data = fs.readJSONSync(packageResource);
                                }
                                catch (error) {
                                    data = fs.readJSONSync(path.join(__dirname, 'mock', 'module-enhancer-script.json'));
                                }
                                resolve(_this.createAxiosResponse(data));
                            })];
                    case 2:
                        _b = _e.sent();
                        return [3 /*break*/, 8];
                    case 3:
                        if (!this.packageDetailCache[key]) return [3 /*break*/, 5];
                        return [4 /*yield*/, new Promise(function (resolve, reject) {
                                resolve(_this.createAxiosResponse(_this.packageDetailCache[key]));
                            })];
                    case 4:
                        _c = _e.sent();
                        return [3 /*break*/, 7];
                    case 5: return [4 /*yield*/, axios_1.default.get("/" + this.name2url({ scope: scope, packageName: packageName }))];
                    case 6:
                        _c = _e.sent();
                        _e.label = 7;
                    case 7:
                        _b = _c;
                        _e.label = 8;
                    case 8:
                        packageDetailResponse = _b;
                        if (!process.env.MOCK) return [3 /*break*/, 10];
                        return [4 /*yield*/, new Promise(function (resolve) {
                                var packageResource = path.join(__dirname, 'mock', packageName + ".readme.md");
                                var data;
                                try {
                                    data = _this.readme2Html(packageResource);
                                }
                                catch (error) {
                                    data = _this.readme2Html(path.join(__dirname, 'mock', 'module-enhancer-script.readme.md'));
                                }
                                resolve({
                                    readme: data,
                                    fileList: [],
                                });
                            })];
                    case 9:
                        _d = _e.sent();
                        return [3 /*break*/, 12];
                    case 10: return [4 /*yield*/, new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
                            var packageDetail, downloadUrl, storageDir;
                            var _this = this;
                            return __generator(this, function (_a) {
                                packageDetail = packageDetailResponse.data;
                                downloadUrl = packageDetail.versions[currentVersion].dist.tarball;
                                storageDir = path.join(this.tmpDir, scope, packageName, currentVersion);
                                if (fs.existsSync(storageDir)) {
                                    this.readAdditionalCode(storageDir).then(function (response) {
                                        resolve(response);
                                    });
                                }
                                else {
                                    axios_1.default
                                        // Request package:
                                        .request({
                                        responseType: 'arraybuffer',
                                        url: downloadUrl,
                                        method: 'get',
                                        headers: {
                                            'Content-Type': 'application/gzip',
                                        },
                                    })
                                        // Store package in filesystem:
                                        .then(function (result) {
                                        fs.ensureDirSync(storageDir);
                                        var outputFilename = path.join(storageDir, packageName + "-" + currentVersion + ".tar.gz");
                                        fs.writeFileSync(outputFilename, result.data);
                                        return outputFilename;
                                    })
                                        // Extract package:
                                        .then(function (file) {
                                        var cwd = storageDir;
                                        return tar.x({ file: file, cwd: cwd }).then(function () { return cwd; });
                                    })
                                        .then(function (dir) {
                                        _this.readAdditionalCode(dir).then(function (response) {
                                            resolve(response);
                                        });
                                    });
                                }
                                return [2 /*return*/];
                            });
                        }); })];
                    case 11:
                        _d = _e.sent();
                        _e.label = 12;
                    case 12:
                        additionalCode = _d;
                        Object.assign(packageDetailResponse.data, additionalCode);
                        return [2 /*return*/, new Promise(function (resolve, reject) {
                                if (!_this.packageDetailCache[key]) {
                                    _this.packageDetailCache[key] = Object.assign({ _isCached: true }, packageDetailResponse.data);
                                }
                                resolve(packageDetailResponse);
                            })];
                }
            });
        });
    };
    ArtifactoryService.prototype.getDistTags = function (_a) {
        var _this = this;
        var scope = _a.scope, packageName = _a.packageName;
        return process.env.MOCK
            ? new Promise(function (resolve, reject) {
                resolve(_this.createAxiosResponse({
                    latest: '1.1.0',
                }));
            })
            : axios_1.default.get("/-/package/" + this.name2url({ scope: scope, packageName: packageName }) + "/dist-tags");
    };
    ArtifactoryService.prototype.getFileContent = function (packageId, filepath, format) {
        if (format === void 0) { format = 'string'; }
        return __awaiter(this, void 0, void 0, function () {
            var absPath, fileContent;
            return __generator(this, function (_a) {
                absPath = path.join(this.tmpDir, packageId.scope, packageId.packageName, packageId.version, 'package', filepath);
                fileContent = fs.readFileSync(absPath);
                return [2 /*return*/, format === 'string' ? fileContent.toString() : fileContent];
            });
        });
    };
    ArtifactoryService.prototype.name2url = function (_a) {
        var scope = _a.scope, packageName = _a.packageName;
        return "" + (scope && scope !== 'undefined' ? scope + "/" : '') + packageName;
    };
    ArtifactoryService.prototype.createAxiosResponse = function (data) {
        return {
            data: data,
            status: 200,
            config: undefined,
            headers: undefined,
            request: undefined,
            statusText: undefined,
        };
    };
    ArtifactoryService.prototype.readme2Html = function (readmeFile) {
        var readme;
        try {
            readme = fs.readFileSync(readmeFile);
        }
        catch (error) {
            throw new Error("README file not found: " + readmeFile);
        }
        var emojifiedReadme = emoji.emojify(readme.toString());
        var converter = new showdown.Converter();
        var html = converter.makeHtml(emojifiedReadme);
        return html;
    };
    ArtifactoryService.prototype.readAdditionalCode = function (storageDir) {
        return __awaiter(this, void 0, void 0, function () {
            var readme, fileList, _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        try {
                            readme = this.readme2Html(path.join(storageDir, 'package', 'README.md'));
                        }
                        catch (error) {
                            readme = undefined;
                        }
                        _b.label = 1;
                    case 1:
                        _b.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, fileLister_1.default(storageDir, 'package', false)];
                    case 2:
                        fileList = _b.sent();
                        return [3 /*break*/, 4];
                    case 3:
                        _a = _b.sent();
                        fileList = [];
                        return [3 /*break*/, 4];
                    case 4: return [2 /*return*/, {
                            readme: readme,
                            fileList: fileList,
                        }];
                }
            });
        });
    };
    return ArtifactoryService;
}());
exports.default = new ArtifactoryService();
