"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const promises_1 = require("fs/promises");
const PackedFile_1 = require("./PackedFile");
const spawnPromise_1 = require("./spawnPromise");
const path = require("path");
const fs_1 = require("fs");
class PackedLessFile extends PackedFile_1.default {
    constructor(p) {
        super(p);
        if ((0, fs_1.existsSync)(p)) {
            (0, fs_1.unlinkSync)(p);
        }
        if ((0, fs_1.existsSync)(p + ".css.map")) {
            (0, fs_1.unlinkSync)(p + ".css.map");
        }
    }
    async append(src) {
        // find last map...
        const sourceFile = await this.findSourceFile(src + ".css");
        if (sourceFile) {
            await (0, promises_1.appendFile)(this.path, `@import (less) "${sourceFile}";\n`);
            return;
        }
        // make relative
        src = path.relative(this.dir, src).replaceAll("\\", "/");
        await (0, promises_1.appendFile)(this.path, `@import (less) "${src}.css";\n`);
    }
    async findSourceFile(filePath) {
        try {
            const dir = path.dirname(filePath);
            const fileContent = await (0, promises_1.readFile)(filePath, "utf-8");
            let lastLine = null;
            for (const m of fileContent.matchAll(/[^\n]+/g)) {
                lastLine = m[0] || lastLine;
            }
            let mapFile = null;
            for (const m of lastLine.matchAll(/((\/\/)|(\/\*))\s{0,5}(#\s{0,5}sourceMappingURL\s{0,5}\=)(?<map>[^\s]+)/g)) {
                mapFile = m.groups?.map ?? mapFile;
            }
            if (mapFile) {
                const fullMapPath = path.join(dir, mapFile);
                if ((0, fs_1.existsSync)(fullMapPath)) {
                    const json = JSON.parse(await (0, promises_1.readFile)(fullMapPath, "utf-8"));
                    const sources = json?.sources;
                    if (sources?.length === 1) {
                        const mapFileSource = sources[0];
                        const mapFileDir = path.dirname(fullMapPath);
                        let sourceFile = path.join(mapFileDir, mapFileSource);
                        if ((0, fs_1.existsSync)(sourceFile)) {
                            // let us make it relative to current file's dir
                            sourceFile = path.relative(this.dir, sourceFile);
                            return sourceFile.replaceAll("\\", "/");
                        }
                    }
                }
            }
        }
        catch {
        }
    }
    async postSave() {
        // convert less to css here
        const lessCPath = path.resolve("node_modules/less/bin/lessc");
        const dir = path.resolve(this.dir).replaceAll("\\", "/") + "/";
        const mapFileName = this.name + ".css.map";
        console.log(this.dir);
        await (0, spawnPromise_1.spawnPromise)(process.execPath, [
            lessCPath,
            "--source-map=" + mapFileName,
            "-ru=all",
            this.name,
            this.name + ".css",
        ], {
            cwd: this.dir
        });
        // fix path...
        const mapFilePath = path.join(this.dir, mapFileName);
        const map = JSON.parse(await (0, promises_1.readFile)(mapFilePath, "utf8"));
        map.sources = map.sources.map((x) => path.isAbsolute(x)
            ? path.relative(dir, x).replaceAll("\\", "/")
            : x);
        await (0, promises_1.writeFile)(mapFilePath, JSON.stringify(map));
    }
}
exports.default = PackedLessFile;
//# sourceMappingURL=PackedLessFile.js.map