import mongo, { Database, Collection } from "then-mongo";

const scoreKeys = ["points", "good", "ok", "bad", "maxCombo", "drumroll"];

class Score {
	original: string;
	available: boolean;
	crown: number;
	points: number;
	good: number;
	ok: number;
	bad: number;
	maxCombo: number;
	drumroll: number;
	constructor(str: string) {
		this.original = str;
		if (!str.length) {
			this.available = false;
			return;
		}
		this.available = true;
		this.crown = parseInt(str.slice(0, 1));
		const components = str.slice(1).split(",");
		for (let i = 0; i < components.length; ++i) {
			this[scoreKeys[i]] = parseInt(components[i], 36);
		}
	}
	toString() {
		if (!this.available) {
			return "";
		}
		const components = scoreKeys.map(key => {
			return this[key].toString(36);
		});
		return `${this.crown}${components.join(",")}`;
	}
}

function replaceString(src: string) {
	const diffs = src.split(";").map(m => new Score(m));
	for (let score of diffs) {
		if (score.crown === 2 && score.ok === 0) {
			score.crown = 3;
		}
	}
	return diffs.map(s => s.toString()).join(";");
}

//console.log(replaceString("2imnw,4h,0,0,4h,k"));

const mongoUrl = process.argv[2];
let col: Collection;

async function updateOne(scoreRow: any) {
	const str = scoreRow.score;
	const newStr = replaceString(str);
	if (str !== newStr) {
		await col.update({ _id: scoreRow._id }, { $set: { score: newStr } });
		console.log(`Score of ${scoreRow.username} ${scoreRow.hash} updated from ${str} to ${newStr}.`);
	}
}

async function main() {
	console.log("Started.");
	const db = mongo(mongoUrl);
	col = db.collection("scores");
	console.log("Checking scores.");
	await col.find().map(updateOne);
	console.log("Finished.");
	process.exit();
}
main();
