// import '@k-core/polyfills';
// import 'zone.js/dist/zone-node';
// import 'reflect-metadata';
// import 'rxjs/Rx';
// import * as path from 'path';
// import * as express from 'express';
// import * as auth from 'http-auth';
// import * as cookieParser from 'cookie-parser'
// import session from 'express-session'
// const XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest

// import { Request, Response } from 'express';
// import { platformServer, renderModuleFactory } from '@angular/platform-server';
// import { ServerAppModule } from './server-app.module';
// import { ngExpressEngine } from '@nguniversal/express-engine';
// import { ROUTES } from './server-routes';
// import { enableProdMode } from '@angular/core';
// import { urlkey } from '@k-settings/app-setup'
// import { storeId } from '@k-settings/store-helper'
// import { DataLayerManager } from '../../../node_modules/@agm/core';
// enableProdMode();

// const url = require('url')
// const app = express();
// const port = process.env.PORT || 8000;
// const baseUrl = `http://localhost:${port}`;
// const cookieTime = 24 * 60 * 60 * 1000

// app.engine('html', ngExpressEngine({
// 	bootstrap: ServerAppModule
// }));

// app.set('view engine', 'html');
// app.set('views', 'src');

// function cacheControl(req, res, next) {
// 	// instruct browser to revalidate in 60 seconds
// 	res.header('Cache-Control', 'max-age=432000');
// 	next();
// }


// // Auth Config
// var USER    = 'Rulle',
// 	PASS    = 'Gardin',
// 	USEAUTH = false;

// var basic = auth.basic({
// 		realm: 'Kake'
// 	}, function(username, password, callback) {
// 		callback(username === USER && password === PASS);
// 	});

// if (USEAUTH) {
// 	app.use(auth.connect(basic));
// }

// /**
//  * **** LOGIN PAGE REDIRECT ****
//  */

// // Define the session secret, TODO: Change this to be a dynamic session secret based on project
// var secret = 'PHPSESSIDBILKA'

// // Session specs
// var sess = {
// 	resave: false,
// 	saveUninitialized: true,
// 	secret: secret,
// 	cookie: {
// 		maxAge: cookieTime
// 	}
// }

// app.set('trust proxy', 1)

// // Define the session code
// app.use(session(sess))
// app.use(cookieParser())
// // Declare XHR, for making XMLHttpRequests, required for Angular
// let xhr = new XMLHttpRequest()


// /**
//  * HTTP_GET for ExpressJS
//  * $
//  * @param url 
//  */
// let HttpGet = (url) => {
// 	xhr.open("GET", url, false)
// 	xhr.send(null)
// 	return JSON.parse(xhr.responseText)
// }

// // Password protection of sub pages
// let passwordProtection = (req: any, res, next) => {



// 	return new Promise(((resolve, reject) => {

// 		let sessionId = req.session.id
// 		let host: string = req.get('host')
// 		var cookie = req.cookies.kakesession

// 		if (cookie === undefined) {
// 			res.cookie('kakesession', req.session.id, { maxAge: cookieTime })
// 		} else {
// 			sessionId = cookie
// 		}

		
		
// 		if(host.indexOf('localhost') === -1)
// 			// expects Protocol to be https, TODO: figure out why req.protocol returns http
// 			resolve(HttpGet('https://' + req.get('host') + '/login/check.php?storeId='+storeId + '&guid=' + sessionId))

// 		else
// 			// Rejects for localhost
// 			reject('localhost')


// 	})).then((response: any) => {
// 		let data = response

// 		if(data.has_login && !data.logged_in)
// 			// does the user need to log in?
// 			res.send('<script>window.location.href="/login?redirect=' + urlkey + '&guid='+ req.session.id +'";</script>');
// 		else
// 			// Log in is not required!
// 			next()
		
// 	}).catch((message) => {
// 		console.log('Trying to load locked scope on ' + message)
// 		next()
// 	})
// }


// /**
//  * Typecasting `req` to `any` so it doesn't fail over `session.id`
//  */
// app.get('*', (req: any, res, next) => {

// 		// passwordProtection(req, res, next)
// 		next()
// })


// // Serve static files
// app.use('/assets', cacheControl, express.static('source/assets', {maxAge: 432000}));
// app.use('/', express.static('dist', {index: false}));


// ROUTES.forEach((route: string) => {
// 	app.get(route, (req: Request, res: Response) => {
// 		console.time(`GET: ${req.originalUrl}`);
// 		res.render('../dist/index', {
// 			req: req,
// 			res: res
// 		});
// 		console.timeEnd(`GET: ${req.originalUrl}`);
// 	});
// });

// app.listen(port, () => {
// 	console.log(`Listening at ${baseUrl}`);
// });


import * as express from 'express';
import * as bodyParser from 'body-parser'; //used to parse the form data that you pass in the request

class App {

    public app: express.Application;


    constructor() {
        //run the express instance and store in app
        this.app = express(); 
        this.config();
    }

    private config(): void {

        // support application/json type post data
        this.app.use(bodyParser.json());

        //support application/x-www-form-urlencoded post data
        this.app.use(bodyParser.urlencoded({
            extended: false
        }));

        this.app.use(function(req, res, next) {
            res.header("Access-Control-Allow-Origin", "*");
            res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
            next()
        })
    }

}

export default new App().app;