import { Undecked } from '../Core';
import { Log } from '../Logger';

declare var Undecked: Undecked;

export class KeyManager {
	ids: string[];

	constructor() {
		this.ids = [];
	}

	register(keyID: string): string {
		if (!this.ids.includes(keyID)) this.ids.push(keyID);
		else {
			Log('warn', `Duplicate key IDs '${keyID}'`);
			keyID = this.generateNew();
		}
		return keyID;
	}

	generateNew() {
		return this.register(
			Undecked.generateRandom(16, (checkValid) => {
				return !this.ids.includes(checkValid);
			})
		);
	}

	getLocation(keyID): { pageID: string; x: number; y: number } {
		var pages = Undecked.Pages.getAll();
		for (var pageID in pages) {
			var page = pages[pageID];
			if (page.hasKeyWithID(keyID)) {
				return { pageID, ...page.getKeyLocationWithID(keyID) };
			}
		}
		return { pageID: null, x: null, y: null };
	}
}
