import fs from 'fs-extra';
import _ from 'lodash';
import * as DataEvent from '../../src/com/events/DataEvent';
import Settings, { SETTINGS_FILE } from './Settings';
const settings = new Settings();

export default class Navigation {
	//--------------------------
	// constructor
	//--------------------------
	constructor() {}
	//--------------------------
	// methods
	//--------------------------
	sync(body) {
		return new Promise((resolve, reject) => {
			let response = [];
			settings
				.load(SETTINGS_FILE)
				.then(settings => {
					let payload = body;
					settings.menu = payload.nav;
					fs.writeJson('site/settings.json', settings)
						.then(() => {
							response = {
								type: DataEvent.SETTINGS_UPDATED,
								message: 'Menu order saved, champ'
							};
							resolve(response);
						})
						.catch(err => {
							response = {
								type: DataEvent.REQUEST_LAME,
								message: err
							};
							reject(response);
						});
				})
				.catch(err => {
					response = {
						type: DataEvent.REQUEST_LAME,
						message: err
					};
					reject(response);
				});
		});
	}

	editMenu(task, item) {
		settings.load(SETTINGS_FILE).then(settings => {
			switch (task) {
				case DataEvent.MENU_ADD_ITEM:
					settings.menu.push({
						title: item.title,
						id: item.id,
						slug: item.slug,
						uuid: item.uuid,
						path: item.path
					});
					break;
				case DataEvent.MENU_DELETE_ITEM:
					settings.menu = _.remove(settings.menu, m => {
						return m.uuid != item.uuid;
					});

					break;
			}
			fs.writeJSON(SETTINGS_FILE, settings);
		});
	}

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