// train.js
var http = require('http');
var trainCache = {
    last: {},
    data: {}
};

module.exports = {



    dbe_glq: function (req, res) {

        console.log('DBE:GLQ request');

        var now = new Date();
        var nowSeconds = (now.getHours() * (60 * 60)) + (now.getMinutes() * 60);
        console.log('Now Seconds: ' + nowSeconds);
        if (trainCache.last.dbeglq == null || nowSeconds != trainCache.last.dbeglq) {
            Query(function (a, b) {

                var ts = a.departures[0].service;
                var output = {};
                console.log(ts);

                console.log(ts.sta);


                output.sta = ts.sta;
                output.eta = ts.eta;
                trainCache.data.dbeglq = output;

                res.setHeader('Content-Type', 'application/json');
                res.end(JSON.stringify(trainCache.data.dbeglq));
            }, res, 'huxley.apphb.com', '/next/dbe/to/glq/1?accessToken=215b99fe-b237-4a01-aadc-cf315d6756d8');

        }
    },
    glq_dbe: function (req, res) {

        console.log('GLQ:DBE request');

        var now = new Date();
        var nowSeconds = (now.getHours() * (60 * 60)) + (now.getMinutes() * 60);
        console.log('Now Seconds: ' + nowSeconds);
        if (trainCache.last.glqdbe == null || nowSeconds != trainCache.last.dbeglq) {
            Query(function (a, b) {

                var ts = a.departures[0].service;
                var output = {};
                console.log(ts);
                //GLOBAL.lastcheck = now;
                console.log(ts.sta);
                console.log(toSeconds(ts.sta));

                output.sta = ts.sta;
                output.eta = ts.eta;
                trainCache.data.glqdbe = output;
                //  trainCache.last.glqdbe = toSeconds(ts.sta);
                //  console.log(ts);
                res.setHeader('Content-Type', 'application/json');
                res.end(JSON.stringify(trainCache.data.glqdbe));
            }, res, 'huxley.apphb.com', '/next/glq/to/dbe/1?accessToken=215b99fe-b237-4a01-aadc-cf315d6756d8');

        }
    },
    getTrainTimes: function(req, res) {
       // console.log(req);
        console.log('getTrainTimes: ' + JSON.stringify(req.query));
        if (req.query.hasOwnProperty('from') && req.query.hasOwnProperty('from'))
        {

        var url = '/all/' + req.query.from + '/to/' + req.query.to + '/10?accessToken=215b99fe-b237-4a01-aadc-cf315d6756d8';

         Query(function (a, b) {
                res.setHeader('Content-Type', 'application/json');
                res.end(JSON.stringify(a));
            }, res, 'huxley.apphb.com', url);
        }
        else{
            res.setHeader('Content-Type', 'application/json');
                res.end(JSON.stringify({}));
        }

    },
    getNextTrainTimes: function(req, res) {
        console.log('getNextTrainTimes: ' + JSON.stringify(req.query));
        var trainFrom, trainTo, trainToken, url;
        if (req.query.hasOwnProperty('from') && req.query.hasOwnProperty('from')) {
            trainFrom = req.query.from;
            trainTo = req.query.to;
            trainToken = trainFrom + trainTo;
            url = '/next/' + trainFrom + '/to/' + trainTo + '/1?accessToken=215b99fe-b237-4a01-aadc-cf315d6756d8';
            console.log('Requesting latest time for : ' + trainToken);

            var now = new Date();
            var nowSeconds = (now.getHours() * (60 * 60)) + (now.getMinutes() * 60);
            console.log('Now Seconds: ' + nowSeconds);
            if (trainCache.last[trainToken] == null || nowSeconds != trainCache.last[trainToken]) {

                Query(function (a, b) {

                    var output = {};
                    var ts = a.departures[0].service;
                    if ( ts !== null)
                    {
                      //  console.log(ts);
                        //GLOBAL.lastcheck = now;
                        console.log(ts.sta);
                        console.log(toSeconds(ts.sta));

                        output.sta = ts.sta;
                        output.eta = (ts.eta !== null ? ts.eta : ts.sta);
                        //  trainCache.last.glqdbe = toSeconds(ts.sta);
                        //  console.log(ts);
                    } else
                    {
                        console.log('*** NO SERVICE');
                        output.sta = 'No Service';
                        output.eta = 'No Service';
                    }

                    trainCache.data[trainToken] = output;

                    res.setHeader('Content-Type', 'application/json');
                    res.end(JSON.stringify(trainCache.data[trainToken]));
                }, res, 'huxley.apphb.com', url);

            }
        }

    }, getRoute: function(req, res) {
        console.log('getRoute: ' + JSON.stringify(req.query));
        var routeID, data={};
        if (req.query.hasOwnProperty('route')) {

            routeID = req.query.route;
            Query(function (a, b) {

               if (a !== null && a.message === null) {
                   data = a;
               }
                res.setHeader('Content-Type', 'application/json');
                res.end(JSON.stringify(data));
            }, res, 'huxley.apphb.com', '/service/' + routeID + '?accessToken=215b99fe-b237-4a01-aadc-cf315d6756d8');
        }

    }
};

function toSeconds(inval) {
    var a = inval.split(':');
    return ((parseInt(a[0]) * (60 * 60)) + (parseInt(a[1]) * 60));

}

function Query(callback, r, host, path) {
    console.log(path);
    var req = r;
    var options = {
        host: host,
        //  port: 80,
        path: path,
        //method: 'GET',
        headers: {}
    };

    try {
        http.request(options).on('response', function (response) {
            var data = '';
            response.on("data", function (chunk) {
                data += chunk;
            });
            response.on('end', function () {
                callback(JSON.parse(data), r);
            });
            response.on('error', function(e) {
                console.error(e);
            });
        }).end();
    } catch (e) {
        console.log(e);
    }
}
