import { writeFile } from 'fs';
import * as path from 'path'
import { Undecked } from './Core';
import { Log } from './Logger';

import * as fs from 'fs-extra';
var { ensureDir, pathExists, readJson } = fs;

declare var Undecked: Undecked;
declare var Config: Config;

export class FileHandler {
	configPath: string;

	constructor() { }

	load(callback: () => void) {
		Log('info', 'Preparing files');
		ensureDir(path.join(Undecked.dataPath), (err) => {
			if (err) throw err;
			this.loadConfig(() => {
				callback();
			});
		});
	}

	loadConfig(callback: () => void) {
		this.configPath = path.join(Undecked.dataPath, 'config.json');
		pathExists(this.configPath, (err, exists) => {
			if (err) throw err;
			if (exists) {
				readJson(this.configPath, (err, json) => {
					if (err) throw err;
					Config = json;
					callback();
				});
			} else {
				Config = defaultConfig;
				this.saveConfig(callback);
			}
		});
	}

	saveConfig(callback?: () => void) {
		writeFile(this.configPath, JSON.stringify(Config, null, 4), (err) => {
			if (err) Log('error', 'Error whilst saving config', err.message);
			if (callback) callback();
		});
	}
}

var defaultConfig: Config = {
	ports: {
		http: 9999
	},
	name: null
};

// export interface FileHandler {
// 	load: (callback: () => void) => void;
// }

export interface Config {
	ports: {
		http: number;
	};
	name: string
}
