const express = require('express');
const router = express.Router();
const FileHound = require('filehound');
const Models = require('../../models');
const fs = require('fs-extra');
var settings = [];
//--------------------------
// SETTINGS
//--------------------------
router.get('/', function(req, res) {
	fs.readJson('config/site-settings.json')
		.then(obj => {
			settings = obj;
		})
		.catch(() => {
			//console.error(err)
		});
	let themes = [];
	FileHound.create()
		.paths('themes')
		.ext('json')
		.find()
		.then(files => {
			files.forEach(file => {
				fs.readJson(file)
					.then(theme => {
						if (theme.name == settings.theme) {
							themes.push({
								theme: theme,
								current: 'true'
							});
						} else {
							themes.push({
								theme: theme,
								current: 'false'
							});
						}
					})
					.catch(() => {
						//console.error(err)
					});
			});
			if (req.session.user) {
				let memberInfo = [];
				Models.User.findById(req.session.user.id).then(user => {
					memberInfo.push({
						handle: user.handle,
						email: user.email,
						avi: user.avatar
					});
					themes.sort(function(a, b) {
						var textA = a.theme.name.toUpperCase();
						var textB = b.theme.name.toUpperCase();
						return textA < textB ? -1 : textA > textB ? 1 : 0;
					});
					res.render('dash/settings', {
						title: 'Dashboard | Settings',
						welcome: 'Your Settings',
						user_status: true,
						themes: themes,
						settings: settings,
						member: memberInfo[0]
					});
				});
			} else {
				res.redirect('/@/dashboard');
			}
		});
});
module.exports = router;
