const { ArgumentParser } = require('argparse')
const fs = require('fs').promises
const syncFs = require('fs')

class Config {
	/**
	 * 
	 * @param {String} path path to config on startup
	 * @param {Object} data Contains actual config data
	 */
	constructor(path, data) {
		this.path = path
		this.data = data
	}

	// TODO: this function basically
	async write_disk() {
		const str = JSON.stringify(this.data, null, 4)
		await fs.writeFile(this.path, str)
	}
}
exports.Config = Config

/**
 * Gets the config data off disk
 * @param {ArgumentParset} parser
 * @returns {Config}
 */
exports.from_cli_parser = function(parser) {

	const args = parser.parse_args()
	const defaultpath = `${process.env.HOME || process.env.USERPROFILE}/.config/freechat/config.json`

	// We'll just assume that the config is there as per the installation process
	const path = (args['config']) ? args['config'] : defaultpath
	let ret = new Config(path, {})

	// Allow errors from here to bubble up instead of handling them

	fs.readFile(path).then(file => {
		const json = JSON.parse(file)

		for(const key of Object.keys(json)) {
			ret.data[key] = json[key]
		}
	})
	.catch(err => console.error(err))

	return ret
}

/**
 * Updates the config with the new object data
 * Called from node's main process
 *
 * @param {Config} config new config data to write
 * @param {String} path | set to 'default' if we're using $HOME/.config/freechat/config.json
 * Set this to anything else to write changes to that specified path
 */
exports.update_file = function(config, path='default') {
	if (path == 'default') {
		path = `${process.env.HOME || process.env.USERPROFILE}/.config/freechat/config.json`
	} else {
		path = path
	}

	const data = JSON.stringify(config, null, 2)
	fs.writeFile(path, data, function(err) {
		if(err) { console.error(err) }
		else { console.log('fine') }
	})
}


