import * as DataEvent from '../../src/com/events/DataEvent';
import fs from 'fs-extra';
const _ = require('lodash');
export const SETTINGS_FILE = 'site/settings.json';
export const SETTINGS_FOLKS = 'site/folks.json';
export const SETTINGS_TAG = 'site/tags.json';

export default class Settings {
	//--------------------------
	// constructor
	//--------------------------
	constructor() {}
	//--------------------------
	// methods
	//--------------------------
	sync(req) {
		let self = this;
		return new Promise((resolve, reject) => {
			self.loadConfigData()
				.then(result => {
					let payload = req.body;
					//so payload matches loaded config
					payload.global.display_limit = result.settings.global.display_limit;
					payload.global.port = result.settings.global.port;
					payload.global.last_backup = result.settings.global.last_backup;
					let user = req.session.user;
					let found = _.find(result.folks, { id: user.id });
					let needToUpdate = false;
					let response = [];
					if (found) {
						let index = found.id - 1;
						if (
							result.folks[index].handle != payload.member.handle ||
							result.folks[index].email != payload.member.email
						) {
							user.handle = payload.member.handle;
							user.email = payload.member.email;
							result.folks[index].handle = payload.member.handle;
							result.folks[index].email = payload.member.email;
							fs.writeJson('site/folks.json', result.folks);
						} else {
							//no need to save
						}
					} else {
						let response = {
							type: DataEvent.REQUEST_LAME,
							message: "You're not logged in, champ"
						};
						reject(response);
					}
					if (!_.isEqual(result.settings.global, payload.global)) {
						let bg = payload.global.background;
						payload.global.background = bg.substr(21, bg.length);
						result.settings.global = payload.global;
						needToUpdate = true;
					} else {
						//no need to save
					}

					if (!_.isEqual(result.settings.email, payload.email)) {
						result.settings.email = payload.email;
						needToUpdate = true;
					} else {
						//no need to save
					}

					if (needToUpdate) {
						fs.writeJson('site/settings.json', result.settings)
							.then(() => {
								response = {
									type: DataEvent.SETTINGS_UPDATED,
									message: 'Settings Saved'
								};
								resolve(response);
							})
							.catch(() => {
								//console.error(err);
							});
					} else {
						//no need to update
					}
				})
				.catch(err => {
					reject(err);
				});
		});
	}
	saveTags(tags) {
		let self = this;
		return new Promise((resolve, reject) => {
			self.load(SETTINGS_TAG)
				.then(config => {
					if (!_.isEqual(config.tags, tags)) {
						config.tags = tags;
						fs.writeJson('site/tags.json', config)
							.then(() => {
								let response = {
									type: DataEvent.SETTINGS_UPDATED,
									message: 'Settings Saved'
								};
								resolve(response);
							})
							.catch(err => {
								reject(err);
							});
					} else {
						let response = {
							type: DataEvent.SETTINGS_NOT_UPDATED,
							message: 'Settings Already Saved'
						};
						resolve(response);
					}
				})
				.catch(err => {
					reject(err);
				});
		});
	}

	updatePageIndex() {
		fs.readJSON('site/settings.json').then(settings => {
			settings.library_stats.current_index = ++settings.library_stats.current_index;
			//settings.library_stats.total_pages = ++settings.library_stats.total_pages;
			fs.writeJSON('site/settings.json', settings);
		});
	}
	load(fileToLoad) {
		return new Promise((resolve, reject) => {
			fs.readJSON(fileToLoad)
				.then(file => {
					resolve(file);
				})
				.catch(err => {
					reject(err);
				});
		});
	}

	loadConfigData() {
		return new Promise((resolve, reject) => {
			let getSettings = this.load(SETTINGS_FILE);
			let getFolks = this.load(SETTINGS_FOLKS);
			Promise.all([getSettings, getFolks])
				.then(result => {
					const [settings, folks] = result;
					let data = { settings: settings, folks: folks };
					resolve(data);
				})
				.catch(err => {
					reject(err);
				});
		});
	}

	//--------------------------
	// event handlers
	//--------------------------
}
