const electron = require('electron');
const path     = require('path');
const fs       = require('fs');

/**
 * System manager.
 */
class UIManager {
	/**
	 * Runs during the installation of the program.
	 *
	 * @return 	Promise
	 */
	static install() {
		return new Promise((resolve, reject) => {
			// get application user data directory
			let userData = UIManager.getUserDataDir();

			// get orders folder
			let orders = path.join(userData, 'orders');

			// make sure the orders folder exists
			if (!fs.existsSync(orders)) {
				// nope, let's create it
				fs.mkdir(orders, (error) => {
					if (error) {
						reject(error);
					} else {
						resolve()
					}
				});
			}
		});
	}

	/**
	 * Runs during the uninstallation of the program.
	 *
	 * @return 	Promise
	 */
	static uninstall() {
		return new Promise((resolve, reject) => {
			// get application user data directory
			let userData = UIManager.getUserDataDir();

			// configure fs options
			let options = {
				recursive: true,
				maxRetries: 1,
			};

			// get orders folder
			let orders = path.join(userData, 'orders');

			// delete folder and all the nested files
			fs.rmdir(orders, options, (error) => {
				if (error) {
					reject(error);
				} else {
					resolve()
				}
			});
		});
	}

	/**
	 * Runs before updating the program.
	 *
	 * @return 	Promise
	 */
	static preflight() {
		return new Promise((resolve, reject) => {
			// do nothing for the moment

			resolve();
		});
	}

	/**
	 * Runs after completing the update of the program.
	 *
	 * @return 	Promise
	 */
	static updated() {
		return new Promise((resolve, reject) => {
			// do nothing for the moment

			resolve();
		});
	}

	/**
	 * Handles unsupported requests.
	 *
	 * @param   string  request  The request type.
	 *
	 * @return 	Promise
	 */
	static unsupported(request) {
		// request not supported, create an empty
		// promise anyway to avoid breaking errors
		return new Promise((resolve, reject) => {
			// lets log the type of request, just out of curiosity
			console.log(request);

			resolve();
		});
	} 

	/**
	 * Returns the path of the folder that contains the
	 * application user data.
	 *
	 * @return string 
	 */
	static getUserDataDir() {
		return (electron.app || electron.remote.app).getPath('userData');
	}
}

// export for external usage
module.exports = UIManager;