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 = 'PHPSESSIDKID'

// 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) => {
	next()
}


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

	console.info('connection from', req.get('host'))
	passwordProtection(req, res, 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}`);
});
