"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
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 };
};
var ModList_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ModList = void 0;
const fs_extra_1 = __importDefault(require("fs-extra"));
const crypto_1 = require("crypto");
const typeorm_1 = require("typeorm");
const Logging_1 = require("./Logging");
let ModList = ModList_1 = class ModList {
    static ensureObject(modList) {
        let a = modList;
        if (a && (a === null || a === void 0 ? void 0 : a.modFileNames))
            return a;
        else if (modList)
            return new ModList_1(modList);
        else
            return new ModList_1({
                name: 'New Modlist',
                desc: 'Created by default',
                mods: []
            });
    }
    static fromModListFile(filepath) {
        return __awaiter(this, void 0, void 0, function* () {
            Logging_1.Logging.log('info', `Loading mod list from ${filepath}`);
            let fd = yield fs_extra_1.default.readJSON(filepath);
            return new ModList_1({
                name: 'New Modlist',
                desc: 'Created from mod-list.json',
                mods: fd.mods.filter((m) => {
                    return m.name !== 'base';
                }).map((m) => {
                    return m.name;
                })
            });
        });
    }
    get modFileNames() {
        return this.mods.map((m) => {
            if (m.endsWith('.zip'))
                return m;
            else
                return m + '.zip';
        });
    }
    get factorioModListFormat() {
        return {
            mods: this.mods.map((m) => {
                return {
                    name: m.split('_')[0],
                    enabled: true
                };
            })
        };
    }
    // writes the mod-list.json file format - filepath should be absolute, and have 'mod-list.json' (or whatever filename) at the end
    writeModListFile(filepath) {
        return __awaiter(this, void 0, void 0, function* () {
            Logging_1.Logging.log('info', `Writing mod list to ${filepath}`);
            yield fs_extra_1.default.writeFile(filepath, JSON.stringify(this.factorioModListFormat, null, 4));
        });
    }
    // takes in an array of mod names, supports many naming types
    // converts name into a name+version object, if no version is specified it will be queried from the API, and the latest version will be locked in
    constructor(params) {
        var _a;
        this.mods = [];
        if (!params)
            return;
        this.id = (_a = params.id) !== null && _a !== void 0 ? _a : (0, crypto_1.randomUUID)();
        this.name = params.name;
        this.desc = params.desc;
        if (!params.mods)
            params.mods = [];
        else if (params.mods.length > 0) {
            for (let i = 0; i < params.mods.length; i++) {
                let mod = params.mods[i];
                // remove .zip if it exists at the end
                mod = mod.endsWith('.zip') ? mod.substring(0, mod.length - 4) : mod;
                // Find the first '.', which will help is identify the version number and string format
                let firstDotIndex = this.name.indexOf('.');
                let lastUnderscoreIndex = this.name.lastIndexOf('_');
                if (firstDotIndex === -1 || lastUnderscoreIndex === -1) {
                    // no version, just mod name itself
                    // check to make sure the version here isn't 'latestl' already - else, add it
                    if (!mod.endsWith('_latest'))
                        mod = mod + '_latest';
                }
                this.mods.push(mod);
            }
        }
    }
    static parseModName(rawName) {
        let mod = rawName;
        mod = mod.endsWith('.zip') ? mod.substring(0, mod.length - 4) : mod;
        // Find the first '.', which will help is identify the version number and string format
        let firstDotIndex = this.name.indexOf('.');
        let lastUnderscoreIndex = this.name.lastIndexOf('_');
        if (firstDotIndex === -1 || lastUnderscoreIndex === -1) {
            // no version, just mod name itself
            // set to latest. When mod caching comes around to check it, will grab latest version and change this
            mod = mod + '_latest.zip';
        }
        return mod;
    }
};
exports.ModList = ModList;
__decorate([
    (0, typeorm_1.PrimaryColumn)(),
    __metadata("design:type", String)
], ModList.prototype, "id", void 0);
__decorate([
    (0, typeorm_1.Column)({
        nullable: true
    }),
    __metadata("design:type", String)
], ModList.prototype, "name", void 0);
__decorate([
    (0, typeorm_1.Column)({
        nullable: true
    }),
    __metadata("design:type", String)
], ModList.prototype, "desc", void 0);
__decorate([
    (0, typeorm_1.Column)({
        nullable: false,
        type: 'simple-array'
    }),
    __metadata("design:type", Array)
], ModList.prototype, "mods", void 0);
exports.ModList = ModList = ModList_1 = __decorate([
    (0, typeorm_1.Entity)('modlist'),
    __metadata("design:paramtypes", [Object])
], ModList);
//# sourceMappingURL=ModList.js.map