import Book from '../../../brain/data/Book';
import Settings, { SETTINGS_FILE } from '../../data/Settings';
const express = require('express');
const router = express.Router();
const _ = require('lodash');
//const settings = require('../../../site/settings.json');
const book = new Book();
const settings = new Settings();
//--------------------------
// SETTINGS
//--------------------------
router.get('/', function (req, res) {
	if (req.session.user) {
		settings
			.load(SETTINGS_FILE)
			.then(settings => {
				var nav = [];
				book.getPage()
					.then(pages => {
						if (settings.menu.length === 0) {
							for (let index = 0; index < pages.length; index++) {
								let item = pages[index].metadata;
								if (item.menu) {
									nav.push({
										id: item.id,
										uuid: item.uuid,
										title: item.title,
										slug: item.slug,
										path: item.path
									});
								}
							}
						} else {
							let newpages = [];
							nav = settings.menu;
							for (let index = 0; index < pages.length; index++) {
								let item = pages[index].metadata;
								if (item.menu)
									newpages.push({
										id: item.id,
										uuid: item.uuid,
										title: item.title,
										slug: item.slug,
										path: item.path
									});
							}
							for (let i = 0; i < newpages.length; i++) {
								if (_.find(nav, { uuid: newpages[i].uuid })) {
									//menu item already exists
								} else {
									nav.push({
										id: newpages[i].id,
										uuid: newpages[i].uuid,
										title: newpages[i].title,
										slug: newpages[i].slug,
										path: newpages[i].path
									});
								}
							}
						}
						res.render('navigation', {
							menu: nav,
							welcome: 'Edit Navigation',
							status: true,
							title: 'Dashboard | Navigation'
						});
					})
					.catch(err => {
						res.render('error', { error: err });
					});
			})
			.catch(err => {
				res.render('error', { error: err });
			});
	} else {
		res.redirect('/@/dashboard');
	}
});
module.exports = router;
