/**
 * Created by 212556710 on 4/28/16.
 */
module.exports = function JsonOutputHook() {
    var Cucumber = require('cucumber');
    require("dotenv").config();

    var Logger = require('./Logger.js');
    var JsonFormatter = Cucumber.Listener.JsonFormatter();
    var json_rally = '';
    var fs = require('fs');
    var dir = './Reports/json_report';
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir);
    }

    var imageCount = 0;
    this.registerListener(JsonFormatter);
    JsonFormatter.log = function (jsonold) {
        json_rally = jsonold;

        fs.writeFileSync('Reports/json_report/rally.json', json_rally);

    };

    this.After(function (scenario, callback) {
        console.log('after scenario');
        if (scenario.isFailed()) {
            Logger.info("Results: Failed");
            browser.takeScreenshot().then(function (png) {
                imageCount += 1;
                var decodedImage = new Buffer(png, "base64").toString("binary");
                fs.writeFile("Reports/image" + imageCount + ".png", decodedImage, 'binary', function (err) {
                    scenario.attach(decodedImage, "image/png");
                    console.log("Attached");
                    callback()
                })
            });
        } else {
            Logger.info("Results: Passed");
            callback();
        }
    });

    this.registerHandler('BeforeScenario', function (event, callback) {
        var scenario = event.getPayloadItem('scenario');
        Logger.info("|--------------------------------------------------------|");
        Logger.info("Test " + scenario.getName() + " has started");
        Logger.info("|--------------------------------------------------------|\r\n");
        callback();
    });

    this.registerHandler('AfterScenario', function (event, callback) {
        var scenario = event.getPayloadItem('scenario');
        Logger.info("|--------------------------------------------------------|");
        Logger.info("Test " + scenario.getName() + " has ended");
        Logger.info("|--------------------------------------------------------|\r\n\r\n");
        callback();
    });

    this.registerHandler('AfterFeatures', function (features, callback) {
        if (json_rally == '') {
            //spin for loop until json rally finished
            var date = new Date();
            while (new Date() - date < 1500) {
                //spin for 1.5 sec
            }
        }
        
        if (process.env.postToRally == "true" || process.env.posttorally == true) {
            let pollingtime = (process.env.statusPollingTime && process.env.statusPollingTime > 0 ) ? process.env.statusPollingTime : 120000 ;

            Logger.debug("Started Rally Posting")
            var request = require("request-promise").defaults({ jar: true });
            var options = {
                method: 'POST',
                url: 'http://10.84.167.108:3000/rally',
                headers: {
                    "framework": "Proui",
                    "Content-Type": "application/json",
                    "updatedTestcases" : process.env.updatedTestcases,
                    "userstory": process.env.user_story ? process.env.user_story : process.env.userstory,
                    "testsetId": process.env.testset ? process.env.testset : process.env.testsetId,
                    "build": process.env.build_no? process.env.build_no : process.env.build,
                    "method": process.env.method,
                    "testtype": process.env.type? process.env.type : process.env.testtype,
                    "tags": process.env.tag ? process.env.tag : process.env.tags,
                    "rallyworkspace": process.env.rallyworkspace,
                    "folderpath": process.env.rallyrootfolder ? process.env.rallyrootfolder : process.env.folderpath,
                    "projectname": process.env.project? process.env.project : process.env.projectname,
                    "apikey": process.env.apiKey,
                    "rallyProxy": process.env.rallyProxy,
                    "overwrite_fp": process.env.overwrite_RF? process.env.overwrite_RF : process.env.overwrite_FP,
                    "overwrite_pn": process.env.overwrite_PN,
                    "overwrite_ts": process.env.overwrite_TS,
                    "overwrite_us": process.env.overwrite_US,
                    "overwrite_build": process.env.overwrite_build,
                    "overwrite_tags": process.env.overwrite_tags,
                    "overwrite_method": process.env.overwrite_method,
                    "overwrite_testtype": process.env.overwrite_testtype,
                    "updateTCR": process.env.overwrite_result ? process.env.overwrite_result : process.env.updateTCR,
                    "createNewTestCases": process.env.createNewTestCases,
                    "generateTrends": process.env.generateTrendsJson ? process.env.generateTrendsJson : process.env.generateTrends,
                    "TrendsModule": process.env.Trends_Module? process.env.Trends_Module : process.env.TrendsModule,
                    "TrendsEnv": process.env.Trends_Env? process.env.Trends_Env : process.env.TrendsEnv,
                    "TrendsJobName": process.env.Trends_JobName ? process.env.Trends_JobName : process.env.TrendsJobName,
                    "AWSS3Proxy": process.env.AWSS3Proxy,
                    "RallyUserName": process.env.RallyUserName
        

                },
                body: JSON.stringify(JSON.parse(json_rally)),
                resolveWithFullResponse: true

            };
            request(options).then(function (response) {
                let statusCheckOptions = {
                    method: 'GET',
                    url: 'http://10.84.167.108:3000' + response.headers.location,
                    resolveWithFullResponse: true
        
                };
                let loop = function () {
                    request(statusCheckOptions).then(function (statusResp){
                        if (statusResp.statusCode === 201) {
                            console.log("Posting Logs: \n---------------------------\n" + statusResp.body);
                            Logger.info("Posting Logs: \n---------------------------\n" + statusResp.body);
                            callback();
                        } else {
                            setTimeout(loop,pollingtime);
                        }
                    }).catch(function (error) {
                        if( error.statusCode === 500 || error.statusCode === 412 || error.statusCode === 400){
                            console.error("Error posting results:\n----------------------\nResponse Logs: \n " + error.error );
                            Logger.error("Error posting results:\n----------------------\nResponse Logs: \n " + error.error );
                            callback();
                        } else {
                            if(error.statusCode != 200 )
                                console.error("Alert ! Error getting status: \n " + error.error );
                            setTimeout(loop,pollingtime);

                        }
                    })
                }
                setTimeout(loop,pollingtime);
                
            }).catch(function (err) {
                console.error("Errors in Submitting request for Posting results \n----------------------\nResponse Logs: \n" + err.error);
                Logger.error("Errors in Submitting request for Posting results \n----------------------\nResponse Logs: \n" + err.error)
                callback();
            });
        } else {
            Logger.info("Not posting results to rally as postToRally is not set to true")
            console.log("Not posting results to rally as postToRally is not set to true");
            callback();
        }
    });
};