"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const promises_1 = __importDefault(require("node:fs/promises"));
const path_1 = __importDefault(require("path"));
const utils = __importStar(require("./../utils/index.js"));
const index_js_1 = __importDefault(require("./../loger/index.js"));
const index_js_2 = __importDefault(require("./../uuid/index.js"));
const File_js_1 = __importDefault(require("./File.js"));
// 使用 require 导入 JSON 配置（兼容 CommonJS）
const { MAX, CACHE_DESC } = require('./config.json');
// 临时存储类（单例模式）
class Temp extends File_js_1.default {
    static type = 'singleton class';
    // 当前临时目录路径
    dir = '';
    // 缓存描述文件路径
    cacheDesc = "";
    // 私有：临时目录路径
    timdir;
    // 私有：当前临时实例 ID
    tempId = null;
    constructor(tempDir) {
        super();
        this.timdir = tempDir;
    }
    // 私有方法：检查目录是否存在
    async #checkDir(dirPath) {
        const exists = await utils.FileExsit(dirPath);
        if (!exists) {
            promises_1.default.mkdir(dirPath);
        }
    }
    // 初始化临时目录
    async init() {
        await this.#checkDir(this.timdir);
        this.cacheDesc = path_1.default.join(this.timdir, CACHE_DESC);
        this.tempId = index_js_2.default.uuid(); // 生成唯一 ID，假设 uuid.uuid() 返回 string
        // 如果缓存文件不存在，则初始化
        if (!(await utils.FileExsit(this.cacheDesc))) {
            await promises_1.default.writeFile(this.cacheDesc, JSON.stringify({ LNnum: 1 }), 'utf-8');
        }
        const waitGen = this.wait(); // AsyncGenerator<boolean, any, unknown>
        let result = await waitGen.next();
        while (!result.done && result.value === false) {
            index_js_1.default.i('temp', '等待中...');
            await utils.sleep(1000);
            result = await waitGen.next();
        }
        const data = result.value;
        if (typeof data == "boolean")
            throw new TypeError("[read generator]");
        const instanceDir = path_1.default.join(this.timdir, this.tempId);
        await promises_1.default.writeFile(this.cacheDesc, JSON.stringify({ LNnum: (typeof data.LNnum == "number" ? data.LNnum : 1) + 1 }), 'utf-8');
        await promises_1.default.mkdir(instanceDir, { recursive: true });
        this.dir = instanceDir;
        // 设为不可枚举 & 不可写
        Object.defineProperty(this, 'cacheDesc', {
            enumerable: false,
            writable: false,
        });
    }
    // 等待并发数低于最大值，返回一个异步生成器
    async *wait() {
        while (true) {
            const data = JSON.parse((await promises_1.default.readFile(this.cacheDesc)).toString());
            if (typeof data.LNnum !== "number")
                throw new Error("[temp error]: cannot load config");
            const currentLnNum = data?.LNnum ?? 1;
            if (currentLnNum <= MAX) {
                return data;
            }
            index_js_1.default.i('TEMP', 'INFO: CONCURRENCY >= MAX_CONCURRENCY', {
                MAX_CONCURRENCY: MAX,
            });
            yield false;
            await utils.sleep(1000);
        }
    }
    // 清理临时目录
    async remove() {
        if (this.tempId === null || this.dir === '') {
            throw new Error(`Please call init() first before calling remove().`);
        }
        try {
            await promises_1.default.rm(this.dir, { recursive: true, force: true });
            const data = JSON.parse(await promises_1.default.readFile(this.cacheDesc, "utf-8"));
            const newCount = Math.max((data?.LNnum || 1) - 1, 0);
            await promises_1.default.writeFile(this.cacheDesc, JSON.stringify({ LNnum: newCount }), 'utf-8');
        }
        catch (err) {
            index_js_1.default.e('TEMP', 'Error during temp dir removal:', err);
        }
        finally {
            // 重置状态
            this.dir = '';
            this.tempId = null;
        }
    }
}
// 导出默认类
exports.default = Temp;
