import _ from "lodash";
import jinja from "jinja-js";
import { promises as fs } from "fs";

export interface Banlist {
	name: string
	list: number[][]
}

export async function generateBanlistFromCode(banlists: Banlist[]) {
	const template = await fs.readFile("./templates/lflist.conf.j2", "utf-8");
	return jinja.render(template, { banlists });
}

export async function readLFList(content: string): Promise<Banlist[]> {
	const lines = content.split("\n");
	const ret: Banlist[] = [];
	let name = "";
	let list: number[][] = [];
	const nextList = (nextName: string) => { 
		if (list.length > 0) { 
			ret.push({ name, list });
		}
		list = [];
		name = nextName;
	}
	for (let line of lines) {
		if (line.startsWith("#")) {
			continue;
		}
		if(line.startsWith("!")) {
			nextList(line.slice(1));
			continue;
		}
		// xxxxxxxx 0
		// use regex to match
		const match = line.match(/^(\d{4,})\s(\d)/);
		if(!match) {
			continue;
		}
		const code = parseInt(match[1]);
		const status = parseInt(match[2]);
		list[status] ??= [];
		list[status].push(code);
	}
	nextList('');
	return ret;
}

export function mergeBanlists(lists: Banlist[], name?: string): Banlist {
	const ret: Banlist = { name: name || lists[0].name, list: [] };
	const existingCodes = new Set<number>();
	for (let status = 0; status < 3; ++status) {
		for (let list of lists) {
			ret.list[status] ??= [];
			for(let code of list.list[status] ?? []) {
				if (!existingCodes.has(code)) {
					ret.list[status].push(code);
					existingCodes.add(code);
				}
			}
		}
	}
	return ret;
}
