'use strict';

const fs = require('fs');
const path = require('path');

const REL = 'temp/.lme-bake-ignore.json';
const DEFAULT_MS = 3500;

function ignoreFilePath(projectPath) {
    return path.join(projectPath || Editor.Project.path, REL);
}

function readAll(projectPath) {
    const fp = ignoreFilePath(projectPath);
    try {
        const data = JSON.parse(fs.readFileSync(fp, 'utf8'));
        return data && typeof data === 'object' ? data : {};
    } catch {
        return {};
    }
}

function writeAll(data, projectPath) {
    const fp = ignoreFilePath(projectPath);
    fs.mkdirSync(path.dirname(fp), { recursive: true });
    fs.writeFileSync(fp, JSON.stringify(data), 'utf8');
}

function markBakePending(levelId, durationMs, projectPath) {
    const ms = Number(durationMs) > 0 ? Number(durationMs) : DEFAULT_MS;
    const data = readAll(projectPath);
    data[String(levelId)] = Date.now() + ms;
    writeAll(data, projectPath);
}

function shouldIgnoreImport(levelId, projectPath) {
    const key = String(levelId);
    const data = readAll(projectPath);
    const until = data[key];
    if (!until) return false;
    if (until > Date.now()) return true;
    delete data[key];
    writeAll(data, projectPath);
    return false;
}

module.exports = {
    markBakePending,
    shouldIgnoreImport,
};
