import { Microservice } from "@autoplex/microservice";
import * as services from "./services";
import { User, RegisterToken } from "@autoplex/database";

/**
 * The main application class
 */
export default class Application extends Microservice
{
	/**
	 * The application key used for signing stuff
	 */
	public readonly APP_KEY: string;

	/**
	 * Get the singleton application instance
	 */
	public static instance() { return <Application>super.instance(); }

	/**
	 * Create a new application instance
	 */
	public constructor(appKey: string) {
		super();
		this.APP_KEY = appKey;
		this.installServices(Object.values(services));
	}

	/**
	 * Initialize the application if necessary
	 */
	protected async onStart() {
		let numUsers = await User.count();
		if (numUsers == 0) {
			console.log("Found 0 users");
			let token = await RegisterToken.findOne();
			if (token === undefined) {
				token = await RegisterToken.generate();
			}
			console.log("First time register with: ", token.token);
		}
	}
}
