"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MoveToml = void 0;
const fs_1 = __importDefault(require("fs"));
class MoveToml {
    constructor(tomlPathOrStr) {
        let tomlStr = tomlPathOrStr;
        try {
            tomlStr = fs_1.default.readFileSync(tomlPathOrStr, "utf8").toString();
        }
        catch (e) { }
        this.toml = MoveToml.parse(tomlStr);
    }
    addRow(sectionName, key, value) {
        if (!MoveToml.isValidValue(value)) {
            if (/^\S+$/.test(value)) {
                value = `"${value}"`;
            }
            else {
                throw new Error(`Invalid value "${value}"`);
            }
        }
        const section = this.forceGetSection(sectionName);
        section.rows.push({ key, value });
        return this;
    }
    getSectionNames() {
        return this.toml.map((s) => s.name);
    }
    isPublished() {
        return !!this.getRow("package", "published-at");
    }
    removeRow(sectionName, key) {
        const section = this.forceGetSection(sectionName);
        section.rows = section.rows.filter((r) => r.key !== key);
        return this;
    }
    serialize() {
        let tomlStr = "";
        for (let i = 0; i < this.toml.length; i++) {
            const section = this.toml[i];
            tomlStr += `[${section.name}]\n`;
            for (const row of section.rows) {
                tomlStr += `${row.key} = ${row.value}\n`;
            }
            if (i !== this.toml.length - 1) {
                tomlStr += "\n";
            }
        }
        return tomlStr;
    }
    updateRow(sectionName, key, value) {
        if (!MoveToml.isValidValue(value)) {
            if (/^\S+$/.test(value)) {
                value = `"${value}"`;
            }
            else {
                throw new Error(`Invalid value "${value}"`);
            }
        }
        const row = this.forceGetRow(sectionName, key);
        row.value = value;
        return this;
    }
    static isValidValue(value) {
        value = value.trim();
        return ((value.startsWith('"') && value.endsWith('"')) ||
            (value.startsWith("{") && value.endsWith("}")) ||
            (value.startsWith("'") && value.endsWith("'")));
    }
    static parse(tomlStr) {
        const toml = [];
        const lines = tomlStr.split("\n");
        for (const line of lines) {
            // Parse new section
            const sectionMatch = line.trim().match(/^\[(\S+)\]$/);
            if (sectionMatch && sectionMatch.length === 2) {
                toml.push({ name: sectionMatch[1], rows: [] });
                continue;
            }
            // Otherwise, parse row in section. We must handle two cases:
            //  1. value is string, e.g. name = "MyPackage"
            //  2. value is object, e.g. Sui = { local = "../sui-framework" }
            const rowMatch = line.trim().match(/^([a-zA-Z_\-]+) = (.+)$/);
            if (rowMatch && rowMatch.length === 3) {
                toml[toml.length - 1].rows.push({
                    key: rowMatch[1],
                    value: rowMatch[2],
                });
            }
        }
        return toml;
    }
    forceGetRow(sectionName, key) {
        const section = this.forceGetSection(sectionName);
        const row = section.rows.find((r) => r.key === key);
        if (row === undefined) {
            throw new Error(`Row "${key}" not found in section "${sectionName}"`);
        }
        return row;
    }
    forceGetSection(sectionName) {
        const section = this.getSection(sectionName);
        if (section === undefined) {
            throw new Error(`Section "${sectionName}" not found`);
        }
        return section;
    }
    getRow(sectionName, key) {
        const section = this.getSection(sectionName);
        return section && section.rows.find((r) => r.key === key);
    }
    getSection(sectionName) {
        return this.toml.find((s) => s.name === sectionName);
    }
}
exports.MoveToml = MoveToml;
