/**
 * Created by Martin on 31/03/2016.
 */
var STRING = require('string');
var logger = require('log4js').getLogger();
var request = require('request'), cheerio = require('cheerio');
var _ = require('lodash');
var trainList = [
    {
        id: 'dbeglq',
        url: 'http://www.journeycheck.com/scotrail/route?from=DBE&to=GLQ&action=search&savedRoute='
    },
    {
        id: 'glqdbe',
        url: 'http://www.journeycheck.com/scotrail/route?from=GLQ&to=DBE&action=search&savedRoute='
    }
];

module.exports = {

    processTrainUpdates: function (body) {
        var outputArray = [];
        var $ = cheerio.load(body);
        var lu = $('DIV#LU').first();

        var us = lu.find('.updatesSection').first();
        us.find('.updateTitle').each(function (div) {
            var wO = {title: '', description: ''};
            title = $(this).find('A').first().text().trim();
            wO.title = title;
            outputArray.push(wO);
        });

        us.find('.updateBodyStart').each(function (div) {

            var description = $(this).find('.bodyInner').first().find('.primaryStyle').first().text().trim();
            var splitDesc = description.split('\r\n');

            var wa = [];
            for (var i = 0; i < splitDesc.length; i++) {
                var contentCheck = splitDesc[i].trim();
                if (contentCheck.indexOf('Impact') > -1) contentCheck = '';
                if (contentCheck.indexOf('Additional Information') > -1) contentCheck = '';
                if (contentCheck.indexOf('apologise for the delay') > -1) contentCheck = '';
                if (contentCheck.indexOf('Delay Repay') > -1) contentCheck = '';
                if (contentCheck.length > 0) wa.push(contentCheck);
            }
            description = wa.join(' ');
            outputArray[div].description = description;
        });

        return outputArray;

    }, getTrainUpdates: function (id, out) {

        return new Promise(function (resolve, reject) {
            "use strict";
            logger.info('Getting train events: ', id);
            var url = trainList[id].url;

            var now = new Date();

            //  if ((now - eventCache.last) > eventCache.expire) {
            request(url, function (err, resp, body) {
                if (err) {
                    //  logger.error(err);
                    return reject(err);
                    // throw err;
                }

                var trainData = module.exports.processTrainUpdates(body);

                for (var i = 0; i < out.length; i++) {
                    var flag = false;
                    for (var j = 0; j < trainData.length; j++) {
                        flag = _.isEqual(trainData[j], out[i])
                    }

                    if (!flag) {
                        trainData.push(out[i]);
                    }
                }
                trainData = _.uniq(trainData);

                return resolve(trainData);

            }, function (error, response, body) {
                if (response.statusCode !== 200) {
                    logger.error(response.statusCode);
                    logger.error(body);
                }
                if (error) {
                    //  logger.error(err);
                    return reject(err);
                    // throw err;
                }
            });

        });

    }, updateTrains: function () {
        logger.info('New Updating trains..');

        var output = [];
        return new Promise(function (resolve, reject) {
            "use strict";
            module.exports.getTrainUpdates(0, [])
                .then((d)=> {
                    "use strict";

                    module.exports.getTrainUpdates(1, d)
                        .then((d)=> {
                            "use strict";
                            return resolve(d);

                        })
                        .catch((e)=> {
                            "use strict";
                            return reject(e);
                        });

                })
                .catch((e)=> {
                    "use strict";
                    return reject(e);
                });
        });

    }

};
