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

module.exports = {

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

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

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

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

            const wa = [];
            for (let i = 0; i < splitDesc.length; i++) {
                let 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);
            const url = trainList[id].url;

            let 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;
                }

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

                for (let i = 0; i < out.length; i++) {
                    let flag = false;
                    for (let 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..');

        let 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);
                });
        });

    }

};
