import { open, Database } from "sqlite";
import sqlite3 from "sqlite3";
import { promises as fs } from "fs";
import { DeckGenerator } from "../src/deck";
import _ from "lodash";

async function openDatabase(path: string) {
	return await open({
		filename: path,
		driver: sqlite3.Database
	});
}

const targetDirectory = process.argv[3];

async function createDirectory() {
	const createDirectoryPaths = [
		targetDirectory
	];
	for (let createDirectoryPath of createDirectoryPaths) {
		try {
			await fs.access(createDirectoryPath);
		} catch (e) {
			await fs.mkdir(createDirectoryPath, { recursive: true });
		}
	}
}
async function generateDecks(main: number[], extra: number[]) {
	const deckGenerator = new DeckGenerator({
		main, extra
	});
	const deckTexts = deckGenerator.getDeckTexts();
	await Promise.all(_.range(deckTexts.length).map(i => fs.writeFile(`${targetDirectory}/${i}.ydk`, deckTexts[i])));
}
async function main() {
	console.log(`Creating directory ${targetDirectory}.`);
	await createDirectory();
	console.log(`Opening database ${process.argv[2]}.`);
	const db = await openDatabase(process.argv[2]);
	console.log(`Reading database ${process.argv[2]}.`);
	const main = (await db.all('select id from datas where (type & 0x4000) = 0 and (type & (0x4000000 | 0x800000 | 0x4000 | 0x2000 | 0x40)) = 0')).map(m => m.id);
	const extra = (await db.all('select id from datas where (type & 0x4000) = 0 and (type & (0x4000000 | 0x800000 | 0x4000 | 0x2000 | 0x40)) > 0')).map(m => m.id);
	console.log(`${main.length} mains and ${extra.length} extras.`);
	await db.close();
	console.log(`Generating decks to ${targetDirectory}.`);
	await generateDecks(main, extra);
}
main();
