
var readJson = function () {

    var fs = require('fs');
    var path = require('path');
    var AWS = require('aws-sdk');
    var logger = require('./Logger.js');
    var proxy = require('proxy-agent');

    this.createTrendsJson = function (callback) {
        try {
            var outputObj = [];
            var filePath = process.cwd();
            var rallyJsonfileName = path.resolve(filePath, 'Reports/json_report/rally.json');

            var rallyLogfileName;
            if (process.env.postToS3WithoutRallyPosting !== "true") {

                rallyLogfileName = path.resolve(filePath, 'Reports/rally-logs.log');
                var textdata = fs.readFileSync(rallyLogfileName, 'utf8').toString();
            }
            var data = fs.readFileSync(rallyJsonfileName, 'utf8')

            var obj = JSON.parse(data);
            var RallyFolderID;
            var dateToAppend = Date.now();
            var currentDate = (new Date()).toISOString().slice(0, 19).replace("T", " ");

            for (var i = 0; i < obj.length; i++) {
                const featureFileName = path.basename(obj[i].uri).replace('.feature', '');
                const featureName = obj[i].name.substring(obj[i].name.lastIndexOf(':') + 1).trim();
                for (var j = 0; j < obj[i].elements.length; j++) {

                    var jsonObj = {};
                    jsonObj["featureName"] = featureName;
                    jsonObj["featureFileName"] = featureFileName;
                    //Reading log file 
                    var ScenarioName = obj[i].elements[j].name, actStr, rallyScenarioName,USScenarioName,SceTestCaseID,TcIdScenarioName,newTestCaseID;
                    if (process.env.postToS3WithoutRallyPosting !== "true") {
                        if (textdata.includes(featureName)) { RallyFolderID = textdata.substring(textdata.indexOf("Test Plan ("), textdata.lastIndexOf(featureName)) }
                        var newFID = RallyFolderID.substring(RallyFolderID.lastIndexOf("Test Plan ("), RallyFolderID.lastIndexOf(')')).replace('Test Plan (', '').trim();
                        if (newFID.includes(featureName)) { newFID = newFID.substring(newFID.indexOf("'"), newFID.indexOf(featureName)).replace('):', '').trim() }
                        jsonObj["RallyFolderID"] = newFID;

                        if (ScenarioName.startsWith("TC") && ScenarioName.includes(":") || ScenarioName.startsWith("US") && ScenarioName.includes(":TC")) {
                            if (ScenarioName.startsWith("US") && ScenarioName.includes(":TC")) {
                                var TempTestCaseID = ScenarioName.substring(ScenarioName.indexOf(':TC') + 1).trim();
                                 SceTestCaseID = TempTestCaseID.substring(0, TempTestCaseID.indexOf(':')).replace(':', '').trim();
                            }
                            else {
                                 SceTestCaseID = ScenarioName.substring(ScenarioName.indexOf('TC'), ScenarioName.indexOf(':')).replace('"', '').trim();
                            }
                            if (textdata.includes(SceTestCaseID))
                                var expStr = textdata.substring(textdata.lastIndexOf(SceTestCaseID) + 1);
                            if (expStr.includes('AM:')) {
                                actStr = expStr.substring(expStr.indexOf(':'), expStr.indexOf('AM:'));
                                rallyScenarioName = actStr.split(/\r?\n/g)[0].replace(':', '');
                            }
                            else {
                                actStr = expStr.substring(expStr.indexOf(':'), expStr.indexOf('PM:'));
                                rallyScenarioName = actStr.split(/\r?\n/g)[0].replace(':', '');
                            }
                            jsonObj['ScenarioName'] = rallyScenarioName.trim();
                        }
                        else if (ScenarioName.startsWith("US") && ScenarioName.includes(":")) {
                            USScenarioName = ScenarioName.substring(ScenarioName.lastIndexOf(':') + 1).trim();
                            jsonObj['ScenarioName'] = USScenarioName;
                        }
                        else {
                            jsonObj['ScenarioName'] = ScenarioName.trim();
                        }
                    }

                    else {
                        if(ScenarioName.startsWith("TC") && ScenarioName.includes(":") || ScenarioName.startsWith("US") && ScenarioName.includes(":")){
                            var expScenarioName = ScenarioName.substring(ScenarioName.lastIndexOf(':') + 1).trim();
                            jsonObj['ScenarioName'] = expScenarioName;
                        }
                        else
                        jsonObj['ScenarioName'] = ScenarioName.trim();
                    }

                    if (process.env.postToS3WithoutRallyPosting !== "true") {
                        if (ScenarioName.startsWith("TC") && ScenarioName.includes(":")) {
                            TestCaseID = ScenarioName.substring(ScenarioName.indexOf('TC'), ScenarioName.indexOf(':')).replace('"', '').trim();
                            jsonObj["TestCaseID"] = TestCaseID;
                        }
                        else if(ScenarioName.startsWith("US") && ScenarioName.includes(":TC") || ScenarioName.startsWith("US")){
                            if(ScenarioName.startsWith("US") && ScenarioName.includes(":TC")){
                                jsonObj["TestCaseID"] = SceTestCaseID.trim();
                            }
                            else {
                                TcIdScenarioName = ScenarioName.substring(ScenarioName.lastIndexOf(':') + 1).trim();
                                TestCaseID = textdata.substring(textdata.indexOf("Test Case ("), textdata.indexOf(TcIdScenarioName));
                                newTestCaseID = TestCaseID.substring(TestCaseID.lastIndexOf("(TC"), TestCaseID.lastIndexOf(")")).replace('(', '').trim();
                                jsonObj["TestCaseID"] = newTestCaseID;
                            }
                        }
                        else if (textdata.includes(ScenarioName)) {
                            TestCaseID = textdata.substring(textdata.indexOf("Test Case ("), textdata.indexOf(ScenarioName));
                             newTestCaseID = TestCaseID.substring(TestCaseID.lastIndexOf("(TC"), TestCaseID.lastIndexOf(")")).replace('(', '').trim();
                            jsonObj["TestCaseID"] = newTestCaseID;
                        }
                    }
                    for (var k = 0; k < obj[i].elements[j].steps.length; k++) {
                        var scenarioStepStatus = obj[i].elements[j].steps[k].result.status;
                        if (scenarioStepStatus === "failed") {
                            break;
                        }
                    }
                    const ss = "ScenarioStatus";
                    jsonObj[ss] = scenarioStepStatus;
                    jsonObj["ExecutionTime"] = currentDate;
                    outputObj.push(jsonObj)
                }
            }

            var re = new RegExp('},', 'g');
            var json = JSON.stringify(outputObj, ',').replace('[', '').replace(new RegExp('},', 'g'), '}\n');
            var updatedjson = json.substring(0,json.lastIndexOf(']'))
            fs.writeFileSync(process.cwd() + '\\Reports\\my_result.json', updatedjson, 'utf8');

            AWS.config.update({
                accessKeyId: 'AKIA5BLUIY5EAHCRDD6D',
                secretAccessKey: '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',
                httpOptions: { agent: proxy(process.env.AWSS3Proxy) }
            });
            var s3 = new AWS.S3();

            if (process.env.Trends_Module != undefined && process.env.Trends_Env != undefined && process.env.Trends_JobName != undefined) {
                var module = process.env.Trends_Module;
                var env = process.env.Trends_Env;
                var jobName = process.env.Trends_JobName;
                var trendsjson = fs.readFileSync(process.cwd() + '\\Reports\\my_result.json', 'utf8')

                console.log('AWS S3 bucket path : QATestResults/ProUI/' + module + '/' + env + '/' + jobName + '_' + dateToAppend + '.json');
                var params = {
                    Bucket: 'digitalone-splunk-data',
                    Key: 'QATestResults/ProUI/' + module + '/' + env + '/' + jobName + '_' + dateToAppend + '.json',
                    Body: trendsjson,
                    ContentType: "application/json"
                };

                s3.putObject(params).promise().then((data) => {
                    if(data)
                        console.log('Successfully posted ' + jobName + '_' + dateToAppend + '.json file in the following AWS S3 bucket path : QATestResults/ProUINxt/' + module + '/' + env);
                        callback();
                    }).catch((error) => {console.log("Error in posting Content [" + error + "]");
                    callback();
                });
            }
            else {
                logger.info('Skipping the trends posting since all the following mandatory environmental variables are not defined in env file : module, environment and job name');
                console.log('Skipping the trends posting since all the following mandatory environmental variables are not defined in env file : module, environment and job name');
            }
        }
        catch (ex) {
            throw 'Exception occured while posting trends data to AWS S3 bucket: ' + ex.stack;
        }
    }
};
module.exports = readJson;
