"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.removeBroadcastInfo = exports.broadcastInfoIndex = exports.addBroadcastInfo = exports.getBroadcastInfo = exports.setLastLoadRss = exports.getLastLoadRss = void 0;
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const index_1 = require("./index");
if (!fs_1.default.existsSync(path_1.default.join(process.cwd(), "/data")))
    fs_1.default.mkdirSync(path_1.default.join(process.cwd(), "/data"));
const db = new index_1.LevelDB(path_1.default.join(process.cwd(), "/data/news"));
async function getLastLoadRss() {
    const result = await db.get("last_load");
    try {
        return result ? new Date(result.toString()) : null;
    }
    catch {
        return null;
    }
}
exports.getLastLoadRss = getLastLoadRss;
async function setLastLoadRss(date) {
    await db.put("last_load", new Date(date).toISOString());
}
exports.setLastLoadRss = setLastLoadRss;
async function getBroadcastInfo() {
    const result = await db.get("broadcast");
    try {
        return JSON.parse(result) || [];
    }
    catch {
        return [];
    }
}
exports.getBroadcastInfo = getBroadcastInfo;
async function addBroadcastInfo(info) {
    const list = await getBroadcastInfo();
    if (broadcastInfoIndex(list, info) === -1) {
        list.push(info);
        await db.put("broadcast", JSON.stringify(list));
        return true;
    }
    return false;
}
exports.addBroadcastInfo = addBroadcastInfo;
function broadcastInfoIndex(list, info) {
    for (let i = 0; i < list.length;) {
        if (list[i].selfId === info.selfId &&
            list[i].channelId === info.channelId)
            return i;
        i++;
    }
    return -1;
}
exports.broadcastInfoIndex = broadcastInfoIndex;
async function removeBroadcastInfo(info) {
    const list = await getBroadcastInfo();
    let i = broadcastInfoIndex(list, info);
    while (i >= 0) {
        list.splice(i, 1);
        i = broadcastInfoIndex(list, info);
    }
    await db.put("broadcast", JSON.stringify(list));
}
exports.removeBroadcastInfo = removeBroadcastInfo;
