const express = require('express');
const router = express.Router();
const Models = require('../../models');
const fs = require('fs-extra');
const _ = require('lodash');
var settings = [];
//--------------------------
// SETTINGS
//--------------------------
router.get('/', function(req, res) {
	fs.readJson('config/site-settings.json')
		.then(obj => {
			settings = [];
			settings = obj;
		})
		.catch(() => {
			//console.error(err)
		});
	if (req.session.user) {
		Models.User.findById(req.session.user.id).then(() => {
			Models.FreshPost.findAll({
				order: [['id', 'DESC']]
			})
				.then(posts => {
					let pages = [];
					if (settings.menu.length == 0) {
						for (let index = 0; index < posts.length; index++) {
							let item = posts[index].post;
							if (item.page == true || item.page == 'true')
								pages.push({
									id: posts[index].id,
									uuid: posts[index].post.uuid,
									title: posts[index].post.title,
									slug: posts[index].post.slug
								});
						}
					} else {
						let newpages = [];
						pages = settings.menu;
						for (let index = 0; index < posts.length; index++) {
							let item = posts[index].post;
							if (item.page == true || item.page == 'true')
								newpages.push({
									id: posts[index].id,
									uuid: posts[index].post.uuid,
									title: posts[index].post.title,
									slug: posts[index].post.slug
								});
						}
						for (let i = 0; i < newpages.length; i++) {
							if (
								_.findIndex(pages, function(o) {
									return o.id == newpages[i].id;
								}) != -1
							) {
								//console.log("FOUND")
							} else {
								pages.push({
									id: newpages[i].id,
									uuid: newpages[i].uuid,
									title: newpages[i].title,
									slug: newpages[i].slug
								});
							}
						}
					}
					res.render('dash/navigation', {
						pages: pages,
						welcome: 'Edit Navigation',
						user_status: true,
						title: 'Dashboard | Navigation'
					});
				})
				.catch(() => {
					//console.log('ERROR', err);
				});
		});
	} else {
		res.redirect('/@/dashboard');
	}
});
module.exports = router;
