import Settings, { SETTINGS_FILE } from '../../data/Settings';
const express = require('express');
const router = express.Router();
const FileHound = require('filehound');
const fs = require('fs-extra');
const settings = new Settings();
const moment = require('moment');
var config = [];
//--------------------------
// SETTINGS
//--------------------------
router.get('/', function (req, res) {
	settings
		.load(SETTINGS_FILE)
		.then(obj => {
			config = obj;
		})
		.catch(err => {
			res.render('error', { error: err });
		});
	loadThemes()
		.then(themes => {
			if (req.session.user) {
				let memberInfo = [];
				let user = req.session.user;
				memberInfo.push({
					handle: user.handle,
					email: user.email,
					avi: user.avi
				});
				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('settings', {
					title: 'Dashboard | Settings',
					welcome: 'Your Settings',
					status: true,
					themes: themes,
					settings: config,
					last_backup: moment(config.global.last_backup).fromNow(),
					member: memberInfo[0]
				});
			} else {
				res.redirect('/@/dashboard');
			}
		})
		.catch(err => {
			res.render('error', { error: err });
		});
});
module.exports = router;

function loadThemes() {
	return new Promise((resolve, reject) => {
		settings
			.load(SETTINGS_FILE)
			.then(settings => {
				FileHound.create()
					.paths('content/themes')
					.ext('json')
					.find()
					.then(files => {
						let themes = [];
						for (let index = 0; index < files.length; index++) {
							fs.readJSON(files[index], (err, theme) => {
								if (theme.name == settings.global.theme) {
									themes.push({
										theme: theme,
										current: 'true'
									});
								} else {
									themes.push({
										theme: theme,
										current: 'false'
									});
								}
							});
						}
						setTimeout(() => {
							resolve(themes);
						}, 200);
					})
					.catch(err => {
						reject(err);
					});
			})
			.catch(err => {
				reject(err);
			});
	});
}
