<commit_before>/*
	Copyright (c) 2016 Team 9: <NAME>, Paige, Elliot, David

	Permission is hereby granted, free of charge, to any person, except one that is enrolled
	in SWEN301: Structured Methods at Victoria University of Wellington,
	obtaining a copy of this software and associated documentation files (the "Software"),
	to deal in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in all
	copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
	SOFTWARE.

*/


var express = require('express'),
    bodyParser = require('body-parser'),
    cookieParser = require('cookie-parser'),
    nunjucks = require('nunjucks'),
    assert = require('assert'),
    session = require('express-session'),
    Database = require('./database/database').Database,
    //following are used to interact with the database.
    Company = require('./database/company'),
    Mail = require('./database/mail').Mail,
    Location = require('./database/location'),
    Route = require('./database/routes'),
    Price = require('./database/customerprice'),
    Managers = require('./database/managers'),
    Graph = require('./database/graph'),
    logFile = require('./database/logFile.js').logFile;
    findRoute = Graph.findRoute;


// Set up express
app = express();
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
app.use('/static', express.static(__dirname + '/static'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cookieParser());
app.use(session({secret: 'apparentlythishastobeaverylongsessionsecret', resave: false, saveUninitialized: true}));

/*
 Configure nunjucks to work with express
 Not using consolidate because I'm waiting on better support for template inheritance with
 nunjucks via consolidate. See: https://github.com/tj/consolidate.js/pull/224
*/
var env = nunjucks.configure('views', {
    autoescape: true,
    express: app
});
/*
    Custom methods for nunjucks
 */
var nunjucksEnv = new nunjucks.Environment();

env.addFilter('isMailOrigin', function(locationid, mail) {
    return mail ? locationid == mail.origin : false;
});

env.addFilter('isMailDestination', function(locationid, mail) {
    return mail ? locationid == mail.destination : false;
});

env.addFilter('round', function(value){
    value = parseInt(value);
    return value.toFixed(2);
});

var nunjucksDate = require('nunjucks-date');
nunjucksDate.setDefaultFormat('YYYY-MM-DD, hh:mm:ss');
env.addFilter("date", nunjucksDate);

var router = express.Router();


/**
 * Initialise the database.
 */
var database = new Database().init();
Mail = new Mail();

//Graph.loadGraph();

// redirects to the stats page by default, this could be another page.
router.get("/", function(req, res) {
   res.redirect('/stats/0')
});

// sets date range as default it you go to stats page without a range entered
router.get("/stats", function(req, res) {
    res.redirect('/stats/0');
});

// Stats page
router.get("/stats/:dateOffset", function(req, res) {
	"use strict";

    Mail.getMailStats(req.params.dateOffset, function(labels, series, range, prev, next, weekTotal, mailAmount, criticalRoutes){
        res.render('index', {
            title: 'Business Figures',
            loggedin: req.session.manager ? true : false,
            homeActive: true,
            labels: labels,
            series: series,
            dateRange: range,
            prevDate: prev,
            nextDate: next,
            weekTotal: weekTotal,
            mailAmount: mailAmount,
            criticalRoutes: criticalRoutes
        });
    });

    //res.render('index',{title: "Dashboard", homeActive: true});
});

// Login page
router.get("/login", function (req, res) {
    "use strict";
    res.render('login', {});
});

router.post("/login", function(req, res) {
    console.log(req.body);
    var manager = req.body;
    var username = req.body.username;
    var password = <PASSWORD>;
    Managers.loginManager(username, password, function(result){
        if (result){
            req.session.manager = manager; //save user in session
            res.render("index", {loggedin: req.session.manager ? true : false});
        } else {
            res.render("index", {loggedin: req.session.manager ? true : false, error: "Invalid code."});
        }

    });
});

router.get("/logFile", function (req, res) {
    "use strict";
    new logFile().loadXMLDoc(function (json) {
        console.log("in callback");
        console.log(json.events.event);
        if (req.session.manager) {
            // res.send(JSON.parse(json));
            res.render('logFile', {events: json.events.event, loggedin: req.session.manager ? true : false});
        }
        else {
            res.render('login', {loggedin: req.session.manager ? true : false});
        }
    });
});

router.get("/logFile/:logFileId", function(req, res){
    var index = req.params.logFileId-1;
    new logFile().loadXMLDoc(function (json) {
        var totalcustomercost = 0;
        var totalbusinesscost = 0;
        //var event = json.events.event;
        console.log("in logfile id");
        console.log(json.events.event.data);
        for (var i = 0; i < (index + 1); i++){
            var event = json.events.event[i];
            console.log(event);
            var data = event.data[0];
            if (data.totalcustomercost){
                console.log("TCC: " + totalcustomercost);
                console.log("PARSE: " + parseInt(data.totalcustomercost[0]));
                totalcustomercost += parseInt(data.totalcustomercost[0]);
                console.log("TCC2: " + totalcustomercost);
            }
            if (data.totalbusinesscost){
                console.log("TBC: " + totalbusinesscost);
                console.log("PARSE: " + parseInt(data.totalbusinesscost[0]));
                totalbusinesscost += parseInt(data.totalbusinesscost[0]);
                console.log("TBC2: " + totalbusinesscost);
            }
            
        }
        //1. calculate business figures
        //2. show events[i]
        res.render('logs', {customercost: totalcustomercost, businesscost: totalbusinesscost, events: json.events.event[index],index: index + 1, loggedin: req.session.manager ? true : false});
    });
});

router.get("/logout",function(req,res) {
    "use strict";
    req.session.manager = null;
    res.render('index', {loggedin: req.session.manager ? true : false});
});<commit_msg>Removed console logs and added some calculations for logs<commit_after>/*
	Copyright (c) 2016 Team 9: <NAME>, Paige, Elliot, David

	Permission is hereby granted, free of charge, to any person, except one that is enrolled
	in SWEN301: Structured Methods at Victoria University of Wellington,
	obtaining a copy of this software and associated documentation files (the "Software"),
	to deal in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in all
	copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
	SOFTWARE.

*/


var express = require('express'),
    bodyParser = require('body-parser'),
    cookieParser = require('cookie-parser'),
    nunjucks = require('nunjucks'),
    assert = require('assert'),
    session = require('express-session'),
    Database = require('./database/database').Database,
    //following are used to interact with the database.
    Company = require('./database/company'),
    Mail = require('./database/mail').Mail,
    Location = require('./database/location'),
    Route = require('./database/routes'),
    Price = require('./database/customerprice'),
    Managers = require('./database/managers'),
    Graph = require('./database/graph'),
    logFile = require('./database/logFile.js').logFile;
    findRoute = Graph.findRoute;


// Set up express
app = express();
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
app.use('/static', express.static(__dirname + '/static'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cookieParser());
app.use(session({secret: 'apparentlythishastobeaverylongsessionsecret', resave: false, saveUninitialized: true}));

/*
 Configure nunjucks to work with express
 Not using consolidate because I'm waiting on better support for template inheritance with
 nunjucks via consolidate. See: https://github.com/tj/consolidate.js/pull/224
*/
var env = nunjucks.configure('views', {
    autoescape: true,
    express: app
});
/*
    Custom methods for nunjucks
 */
var nunjucksEnv = new nunjucks.Environment();

env.addFilter('isMailOrigin', function(locationid, mail) {
    return mail ? locationid == mail.origin : false;
});

env.addFilter('isMailDestination', function(locationid, mail) {
    return mail ? locationid == mail.destination : false;
});

env.addFilter('round', function(value){
    value = parseInt(value);
    return value.toFixed(2);
});

var nunjucksDate = require('nunjucks-date');
nunjucksDate.setDefaultFormat('YYYY-MM-DD, hh:mm:ss');
env.addFilter("date", nunjucksDate);

var router = express.Router();


/**
 * Initialise the database.
 */
var database = new Database().init();
Mail = new Mail();

//Graph.loadGraph();

// redirects to the stats page by default, this could be another page.
router.get("/", function(req, res) {
   res.redirect('/stats/0')
});

// sets date range as default it you go to stats page without a range entered
router.get("/stats", function(req, res) {
    res.redirect('/stats/0');
});

// Stats page
router.get("/stats/:dateOffset", function(req, res) {
	"use strict";

    Mail.getMailStats(req.params.dateOffset, function(labels, series, range, prev, next, weekTotal, mailAmount, criticalRoutes){
        res.render('index', {
            title: 'Business Figures',
            loggedin: req.session.manager ? true : false,
            homeActive: true,
            labels: labels,
            series: series,
            dateRange: range,
            prevDate: prev,
            nextDate: next,
            weekTotal: weekTotal,
            mailAmount: mailAmount,
            criticalRoutes: criticalRoutes
        });
    });

    //res.render('index',{title: "Dashboard", homeActive: true});
});

// Login page
router.get("/login", function (req, res) {
    "use strict";
    res.render('login', {});
});

router.post("/login", function(req, res) {
    var manager = req.body;
    var username = req.body.username;
    var password = <PASSWORD>;
    Managers.loginManager(username, password, function(result){
        if (result){
            req.session.manager = manager; //save user in session
            res.render("index", {loggedin: req.session.manager ? true : false});
        } else {
            res.render("index", {loggedin: req.session.manager ? true : false, error: "Invalid code."});
        }

    });
});

router.get("/logFile", function (req, res) {
    "use strict";
    new logFile().loadXMLDoc(function (json) {
        if (req.session.manager) {
            // res.send(JSON.parse(json));
            res.render('logFile', {events: json.events.event, loggedin: req.session.manager ? true : false});
        }
        else {
            res.render('login', {loggedin: req.session.manager ? true : false});
        }
    });
});

router.get("/logFile/:logFileId", function(req, res){
    var index = req.params.logFileId-1;
    new logFile().loadXMLDoc(function (json) {
        var totalcustomercost = 0;
        var totalbusinesscost = 0;
        var totalvolume = 0;
        var totalweight = 0;
        var totalmail = 0;
        //var event = json.events.event;
        console.log("in logfile id");
        var mailEvents = [];
        for (var i = 0; i < (index + 1); i++){
            var event = json.events.event[i];
            var data = event.data[0];
            if (data.totalcustomercost){
                totalcustomercost += parseInt(data.totalcustomercost[0]);
            }
            if (data.totalbusinesscost){
                totalbusinesscost += parseInt(data.totalbusinesscost[0]);
            }
            if (event.type == "mail"){
                totalmail += 1;
            }
            if (data.volume){
                totalvolume += parseInt(data.volume[0]);
            }
            if (data.weight){
                totalweight += parseInt(data.weight[0]);
            }
            if (event.type == "mail"){
                mailEvents.push({
                    event: event
                })
            }
            for (var j = index; j < mailEvents.length; j++){
                var origin = mailEvents.origin[j];
            }
            console.log("MAIL EVENT ARRAY: " + mailEvents);
            console.log("ORIGIN: " + origin);
        }
        //1. calculate business figures
        //2. show events[i]
        res.render('logs',
            {customercost: totalcustomercost,
                businesscost: totalbusinesscost,
                volume: totalvolume,
                weight: totalweight,
                mails: totalmail,
                events: json.events.event[index],
                index: index + 1,
                loggedin: req.session.manager ? true : false});
    });
});

router.get("/logout",function(req,res) {
    "use strict";
    req.session.manager = null;
    res.render('index', {loggedin: req.session.manager ? true : false});
});
{'fraction_non_alphanumeric': 0.13323840520748575, 'fraction_numerical': 0.0040683482506102524, 'mean_word_length': 2.8630172865374544, 'pattern_counts': {'":': 0, '<': 10, '<?xml version=': 0, '>': 7, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '540975', 'n_tokens_mistral': 4200, 'n_tokens_neox': 4100, 'n_words': 1197}