"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 PackedCssFile extends PackedFile_1.default {
    src;
    constructor(p) {
        super(p);
        this.src = p + ".css";
        if ((0, fs_1.existsSync)(p)) {
            (0, fs_1.unlinkSync)(p);
        }
        if ((0, fs_1.existsSync)(p + ".map")) {
            (0, fs_1.unlinkSync)(p + ".map");
        }
        if ((0, fs_1.existsSync)(this.src)) {
            (0, fs_1.unlinkSync)(this.src);
        }
        if ((0, fs_1.existsSync)(this.src + ".map")) {
            (0, fs_1.unlinkSync)(this.src + ".map");
        }
    }
    get isEmpty() {
        if (!(0, fs_1.existsSync)(this.src)) {
            return true;
        }
        const s = (0, fs_1.statSync)(this.src);
        return s.size === 0;
    }
    async append(src) {
        // make relative
        src = path.relative(this.dir, src).replaceAll("\\", "/");
        await (0, promises_1.appendFile)(this.src, `@import "${src}";\n`);
    }
    async postSave() {
        // convert less to css here
        if (this.isEmpty) {
            return;
        }
        if (!(0, fs_1.existsSync)(this.src)) {
            return;
        }
        const postCssPath = path.resolve("node_modules/postcss-cli/index.js");
        const dir = path.resolve(this.dir).replaceAll("\\", "/") + "/";
        const mapFileName = this.name + ".map";
        console.log(this.dir);
        await (0, spawnPromise_1.spawnPromise)(process.execPath, [
            postCssPath,
            this.name + ".css",
            "-o", this.name,
            "--config", process.cwd(),
            "--map"
        ], {
            cwd: this.dir
        });
        // fix path...
        await (0, fs_1.unlinkSync)(this.src);
        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 = PackedCssFile;
//# sourceMappingURL=PackedCssFile.js.map