<commit_before>﻿exports.getJourneyData = function (reqUrl, callback) {
    var https = require('https');
    var xml2js = require('xml2js');
    var url = require('url');
    //var nodeCache = require("node-cache");
    var moment = require('moment');
    //var mongoose = require('mongoose'), Schema = mongoose.Schema;
    var azure = require('azure');
    //var ServiceClient = azure.ServiceClient;
    var uuid = require('node-uuid');

    var lastPollSeconds = 600;
    
    // request API data from NZTA
    //https://infoconnect1.highwayinfo.govt.nz/ic/jbi/SsdfJourney2/REST/FeedService/journey/R04-NB

    var query = url.parse(reqUrl, true).query;
    var ref = query["ref"];

    if (!ref) {
        callback(JSON.parse('{"message":"/journey expects ?ref=REF"}'));
        return;
    }

    var nztaOptions = {
        host: 'infoconnect1.highwayinfo.govt.nz',
        port: 443,
        path: '/ic/jbi/SsdfJourney2/REST/FeedService/journey/' + ref,
        headers: {
            "username": process.env.NztaUsername,
            "password": <PASSWORD>
        }
    };

    https.get(nztaOptions, function (nztaResponse) {
        var nztaData = '';

        nztaResponse.on('data', function (chunk) {
            // chunk response from NZTA
            nztaData += chunk;
            var message = "" + chunk;
            console.log('Received response of ' + message.length + ' bytes from nzta.');
        });

        nztaResponse.on('end', function () {
            // final response, now process data
            console.log('response end.');

            xml2js.parseString(nztaData, function (err, result) {

//                // get from cache
//                var cache = new nodeCache();
//                cache.get(ref, function(cacheErr, cacheResult) {

                var tableService = azure.createTableService(process.env.StorageAccountName,
                    process.env.StorageAccountKey,
                    process.env.StorageAccountTableStoreHost);

                tableService.createTableIfNotExists('journey', function (error) {
                    if (error) {
                        throw 'Could not create table: ' + error;
                    }

                    var query = azure.TableQuery
                        .select()
                        .from('journey')
                        .where('PartitionKey eq ?', 'journeys');

                    tableService.queryEntities(query, function (queryError, entities) {
                        if (queryError) {
                            throw 'Could not query entities: ' + queryError;
                        }

                        var lastJourney;

                        if (entities.length == 0) {
                            lastJourney = {
                                PartitionKey: 'journeys',
                                RowKey: uuid.v4(),
                                averageSpeed: "",
                                minutes: "",
                                pollDateTime: ""
                            };
                        } else {
                            // find the oldest journey
                            var maxPollDate;
                            var j = 0;
                            for (var i = 0; i < entities.length; i++) {
                                if (!maxPollDate) {
                                    maxPollDate = new Date(entities[i].pollDateTime);
                                    j = i;
                                    continue;
                                }
                                if (new Date(entities[i].pollDateTime) > maxPollDate) {
                                    maxPollDate = new Date(entities[i].pollDateTime);
                                    j = i;
                                }
                            }

                            lastJourney = entities[j];
                        }

                        var journey = {
                            PartitionKey: 'journeys',
                            RowKey: uuid.v4(),

                            name: result["tns:findJourneyByReferenceResponse"]["tns:return"][0]["tns:name"][0],

                            averageSpeed: result["tns:findJourneyByReferenceResponse"]["tns:return"][0]["tns:averageSpeed"][0],
                            minutes: result["tns:findJourneyByReferenceResponse"]["tns:return"][0]["tns:lastEstimate"][0],
                            pollDateTime: result["tns:findJourneyByReferenceResponse"]["tns:return"][0]["tns:lastEstimateTime"][0],

                            //TODO:
                            lastAverageSpeed: lastJourney.averageSpeed,
                            lastMinutes: lastJourney.minutes,<commit_msg>Fixing trend logic.<commit_after>﻿exports.getJourneyData = function (reqUrl, callback) {
    var https = require('https');
    var xml2js = require('xml2js');
    var url = require('url');
    var moment = require('moment');
    var azure = require('azure');
    var uuid = require('node-uuid');

    var lastPollSeconds = 600;
    
    // request API data from NZTA
    //https://infoconnect1.highwayinfo.govt.nz/ic/jbi/SsdfJourney2/REST/FeedService/journey/R04-NB

    var query = url.parse(reqUrl, true).query;
    var ref = query["ref"];

    if (!ref) {
        callback(JSON.parse('{"message":"/journey expects ?ref=REF"}'));
        return;
    }

    var nztaOptions = {
        host: 'infoconnect1.highwayinfo.govt.nz',
        port: 443,
        path: '/ic/jbi/SsdfJourney2/REST/FeedService/journey/' + ref,
        headers: {
            "username": process.env.NztaUsername,
            "password": <PASSWORD>
        }
    };

    https.get(nztaOptions, function (nztaResponse) {
        var nztaData = '';

        nztaResponse.on('data', function (chunk) {
            // chunk response from NZTA
            nztaData += chunk;
            var message = "" + chunk;
            console.log('Received response of ' + message.length + ' bytes from nzta.');
        });

        nztaResponse.on('end', function () {
            // final response, now process data
            console.log('response end.');

            xml2js.parseString(nztaData, function (err, result) {

                var tableService = azure.createTableService(process.env.StorageAccountName,
                    process.env.StorageAccountKey,
                    process.env.StorageAccountTableStoreHost);

                tableService.createTableIfNotExists('journey', function (error) {
                    if (error) {
                        throw 'Could not create table: ' + error;
                    }

                    var query = azure.TableQuery
                        .select()
                        .from('journey')
                        .where('PartitionKey eq ?', 'journeys');

                    tableService.queryEntities(query, function (queryError, entities) {
                        if (queryError) {
                            throw 'Could not query entities: ' + queryError;
                        }

                        var lastJourney;

                        if (entities.length == 0) {
                            lastJourney = {
                                PartitionKey: 'journeys',
                                RowKey: uuid.v4(),
                                averageSpeed: "",
                                minutes: "",
                                pollDateTime: ""
                            };
                        } else {
                            // find the oldest journey
                            var maxPollDate;
                            var j = 0;
                            for (var i = 0; i < entities.length; i++) {
                                if (!maxPollDate) {
                                    maxPollDate = new Date(entities[i].pollDateTime);
                                    j = i;
                                    continue;
                                }
                                if (new Date(entities[i].pollDateTime) < maxPollDate) {
                                    maxPollDate = new Date(entities[i].pollDateTime);
                                    j = i;
                                }
                            }

                            lastJourney = entities[j];
                        }

                        var journey = {
                            PartitionKey: 'journeys',
                            RowKey: uuid.v4(),

                            name: result["tns:findJourneyByReferenceResponse"]["tns:return"][0]["tns:name"][0],

                            averageSpeed: result["tns:findJourneyByReferenceResponse"]["tns:return"][0]["tns:averageSpeed"][0],
                            minutes: result["tns:findJourneyByReferenceResponse"]["tns:return"][0]["tns:lastEstimate"][0],
                            pollDateTime: result["tns:findJourneyByReferenceResponse"]["tns:return"][0]["tns:lastEstimateTime"][0],

                            lastAverageSpeed: lastJourney.averageSpeed,
                            lastMinutes: lastJourney.minutes,
{'fraction_non_alphanumeric': 0.10758590405093864, 'fraction_numerical': 0.006147765945767922, 'mean_word_length': 1.2068798449612403, 'pattern_counts': {'":': 6, '<': 8, '<?xml version=': 0, '>': 6, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 6}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 14, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1393051', 'n_tokens_mistral': 2377, 'n_tokens_neox': 2248, 'n_words': 419}