import { Undecked } from './Core';
import { Log } from './Logger';
import { Config } from './FileHandler';
import { Application, Request } from 'express';
import * as exphbs from 'express-handlebars'
import * as Express from 'express';
import * as path from 'path'
import { pathExists } from 'fs-extra';
import { Server } from 'http';

declare var Undecked: Undecked;
declare var Config: Config;

export class WebServer {
	app: Application;
	constructor() {
		this.app = Express();

		var hbs = exphbs.create({ defaultLayout: 'main/index' });
		this.app.engine('handlebars', hbs.engine);
		this.app.set('view engine', 'handlebars');
		this.app.set('views', path.join(__filename, '..', '..', '..', 'Frontend', 'pages'));
		this.app.set('view options', { layout: 'main/index' });

		var staticDir = path.join(__filename, '..', '..', '..', 'Static');
		this.app.use('/stc', Express.static(staticDir));

		this.app.use('/favicon.ico', Express.static(path.join(staticDir, 'logo', '256.ico')));

		this.app.get(
			[
				'/pd/:pagename/:type',
				'/ld/:pagename/:type'
			],
			(req, res, next) => {
				var pagename: string = req.params.pagename;
				var type: 'style' | 'script' = <any>req.params.type;

				var pagePath = req.url.startsWith('/pd')
					? path.join(__filename, '..', '..', '..', 'Frontend', 'pages', pagename)
					: path.join(__filename, '..', '..', '..', 'Frontend', 'pages', 'layouts', pagename);


				switch (type) {
					case 'style':
						var stylePath = path.join(pagePath, 'style.css');
						pathExists(stylePath, (err, exists) => {
							if (exists == true) res.sendFile(stylePath);
							else next();
						});
						break;

					case 'script':
						var stylePath = path.join(pagePath, 'script.js');
						pathExists(stylePath, (err, exists) => {
							if (exists == true) res.sendFile(stylePath);
							else next();
						});
						break;

					default:
						next();
						break;
				}
			}
		);

		this.app.get('/*', (req, res) => {
			res.render('home', {
				icons: Undecked.Icons.getList(),
				actions: Undecked.Integrations.getActions(),
				connections: Undecked.Integrations.getConnections(),
				connected: Undecked.Connections.getList()
			});
		});
	}

	start(callback: (server: Server) => void) {
		Log('info', 'Preparing WebServer');

		var server = require('http').Server(this.app);
		callback(server);
	}
}

// export interface WebServer {
// 	start: (callback: (server: Server) => void) => void;
// }
