// "Ulimatní" kapp

import { Modul } from "../utils/types";
import { messageReply, messageLinks, wait } from "../utils/utils";

const maxRecurseLength = 10;

function getDepth(id: string, lvl = 0) {
	const pre = messageLinks.get(id);
	if (!pre || lvl >= maxRecurseLength) return lvl;

	return getDepth(pre, lvl + 1);
}

function clear(id: string) {
	const kam = messageLinks.get(id);
	if (!kam) return;

	messageLinks.delete(id);

	return clear(kam);
}

// Garbage collector
const garbageCollectDelay = 60_000;
setInterval(() => {
	for (const klic of messageLinks.keys()) {
		if (Number(BigInt.asUintN(64, BigInt(klic)) >> 22n) + 1420070400000 < Date.now() - garbageCollectDelay)
			messageLinks.delete(klic);
	}
}, garbageCollectDelay);

const exp: Modul = {
	super_on_messageCreate: {
		pos: 2,
		fun: async mes => {
			if (mes.author.id != mes.client.user.id) return false;

			await wait(mes);

			if (getDepth(mes.id) == maxRecurseLength) {
				clear(mes.id);
				messageReply(mes, "nemam rat sarandu");
				return true;
			}

			return false;
		}
	}
};

module.exports = exp;
