# Source: JasmineReporter.js

    /**
     * Created by 212556710 on 4/28/16.
     */
    module.exports = {
        postToRally: function() {
            console.log("I made it inside the reporter")
            var deferred = protractor.promise.defer();
            protractor.promise.controlFlow().execute(function () {
                var fs = require('fs')

                //Used to parse xml
                var parseString = require('xml2js').parseString;
                console.log("About to write jasmine file")

                var convertedJsonObject = new Array();

                // Reading the xml file generated from jasmine
                fs.readFile(path.resolve(__dirname,'./../../../Reports/jasmine.xml'), "UTF-8", function (err, data) {

                    // Using the node_module to convert the xml into a javascript object for easier manipulation
                    parseString(data, function (err, result) {
                        console.log(result.testsuites.testsuite.length)
                        console.dir(JSON.stringify(result));

                        // This loop will iterate through all the test suites (features) and create the JSON object that resembles the cucumber JSON object
                        var iterateThroughJasmineSuites = function (start, done) {

                            if (start < done) {

                                // Grabbing the name of the describe name (Feature Name)
                                var describeName = result.testsuites.testsuite[start].$.name;

                                // Replacing the spaces in the name with dashes
                                var describeId = describeName.replace(/ /g, "-");

                                // This array is the elements array which contains all the scenarios
                                var stepArray = new Array();

                                console.log("Length of steps: " + result.testsuites.testsuite[start].testcase.length)

                                // Another loop which will iterate through all the steps (the "it" statements)
                                var iterateThroughJasmineSteps = function (stepStart, stepDone) {
                                    if (stepStart < stepDone) {

                                        var nameOfItStatement = result.testsuites.testsuite[start].testcase[stepStart]["$"].name;

                                        var idOfItStatement = nameOfItStatement.replace(/ /g, "-");

                                        var durationOfItStatement = result.testsuites.testsuite[start].testcase[stepStart]["$"].time;

                                        if (result.testsuites.testsuite[start].testcase[stepStart].failure != null && typeof result.testsuites.testsuite[start].testcase[stepStart].failure != "unknown") {
                                            var testStatus = "failed"
                                        }
                                        else
                                            var testStatus = "passed"

                                        // This variable is going to hold the array of user stories
                                        var arrUserStory = "";
                                        var testCaseNumber = "";
                                        var testcaseName = "";

                                        //read user story from env file
                                        if (process.env.user_story != undefined && process.env.user_story != "") {
                                            console.log("Assigned env user story")
                                            arrUserStory = process.env.user_story;
                                            arrUserStory = arrUserStory.match(/US[0-9]+/g);
                                        }

                                        //read user story from env file
                                        var checkUserStory = nameOfItStatement.split(":");
                                        if (process.env.overwrite_US == "false" || process.env.overwrite_US == undefined) {

                                            if (checkUserStory.length == 2) {
                                                if (checkUserStory[0].match(/US[0-9]+/g)) {
                                                    arrUserStory = checkUserStory[0];
                                                    arrUserStory = arrUserStory.match(/US[0-9]+/g);
                                                }
                                                else {
                                                    testCaseNumber = checkUserStory[0];
                                                }
                                                testcaseName = checkUserStory[1]
                                            }
                                            // Checking to see if TC number is defined here. Then grabs the right index for the split array to get the user story
                                            else if (checkUserStory.length == 3) {
                                                if (checkUserStory[0].match(/US[0-9]+/)) {
                                                    arrUserStory = checkUserStory[0];
                                                    testCaseNumber = checkUserStory[1]
                                                }
                                                else {
                                                    testCaseNumber = checkUserStory[0]
                                                    arrUserStory = checkUserStory[1];
                                                }
                                                arrUserStory = arrUserStory.match(/US[0-9]+/g);
                                                testcaseName = checkUserStory[2]
                                            }
                                            else {
                                                testcaseName = checkUserStory[0]
                                            }
                                        }
                                        // If env overwrite US is set to true but we still need to get the test case number if there is one
                                        else {
                                            if (checkUserStory.length == 2) {
                                                if (!checkUserStory[0].match(/US[0-9]+/g)) {
                                                    testCaseNumber = checkUserStory[0];
                                                }
                                                testcaseName = checkUserStory[1]
                                            }
                                            // Checking to see if TC number is defined here. Then grabs the right index for the split array to get the user story
                                            else if (checkUserStory.length == 3) {
                                                if (checkUserStory[0].match(/US[0-9]+/)) {
                                                    testCaseNumber = checkUserStory[1]
                                                }
                                                else {
                                                    testCaseNumber = checkUserStory[0]
                                                }
                                                testcaseName = checkUserStory[2]
                                            }
                                            else {
                                                testcaseName = checkUserStory[0]
                                            }
                                        }

                                        // This is to replace the scenario name with the correct userstory whether it got it from the env or feature file

                                        if (arrUserStory != "")
                                            var userStoryString = arrUserStory.join(",");

                                        if (testCaseNumber != "") {
                                            if (userStoryString == undefined && testCaseNumber != undefined) {
                                                userStoryString = testCaseNumber;
                                            }
                                            else {
                                                userStoryString += ":" + testCaseNumber;
                                            }
                                        }

                                        if (checkUserStory.length > 1 && (process.env.overwrite_US == "false" || process.env.overwrite_US == undefined)) {
                                            nameOfItStatement = userStoryString + ":" + testcaseName;
                                        } else if (userStoryString != "" && userStoryString!=undefined) {
                                            nameOfItStatement = userStoryString+":"+testcaseName;
                                        }
                                        else {
                                            nameOfItStatement = checkUserStory[0];
                                        }

                                        var itStatementObject = {
                                            name: nameOfItStatement,
                                            id: describeId + ";" + idOfItStatement,
                                            line: "",
                                            keyword: "Scenario",
                                            description: "",
                                            type: "scenario",
                                            steps: [
                                                {
                                                    name: nameOfItStatement,
                                                    line: "",
                                                    keyword: "Given",
                                                    result: {status: testStatus, duration: durationOfItStatement},
                                                    match: {location: ""}
                                                },
                                                {
                                                    "keyword": "After",
                                                    "hidden": true,
                                                    "result": {
                                                        "status": "passed",
                                                        "duration": 951364
                                                    },
                                                    "match": {
                                                        "location": ""
                                                    }
                                                }
                                            ]
                                        }

                                        //if there are multiple user story.
                                        if (arrUserStory != null && arrUserStory.length > 1) {
                                            console.log("Reached here")
                                            itStatementObject.name = checkUserStory[0].replace(/(,(\s*)?US[0-9]+)+/g, "") + ":" + checkUserStory[1] + "_US_1";
                                            for (var i = 1; i < arrUserStory.length; i++) {
                                                var temp_element = JSON.parse(JSON.stringify(itStatementObject));
                                                var temp_element_userstory = temp_element.name.split(":")[0].replace(/US[0-9]+/g, arrUserStory[i])
                                                temp_element.name = temp_element_userstory + ":" + temp_element.name.split(":")[1].substring(0, temp_element.name.split(":")[1].length - 2) + "_" + (i + 1);
                                                stepArray.push(temp_element);
                                            }
                                        }

                                        stepArray.push(itStatementObject);
                                        iterateThroughJasmineSteps(stepStart + 1, stepDone);
                                    }

                                }

                                iterateThroughJasmineSteps(0, result.testsuites.testsuite[start].testcase.length)

                                // This is Feature object that contains feature name and the test cases for it
                                describeStatementObject = {
                                    id: describeId,
                                    name: describeName,
                                    description: "",
                                    line: "",
                                    keyword: "Feature",
                                    uri: "",
                                    elements: stepArray

                                }

                                convertedJsonObject.push(describeStatementObject);
                                iterateThroughJasmineSuites(start + 1, done);

                            }

                        }

                        iterateThroughJasmineSuites(0, result.testsuites.testsuite.length)

                        fs.writeFile(path.resolve(__dirname,'./../../../Reports/json_report/jasmineRally.json'), JSON.stringify(convertedJsonObject), function (err) {
                            if (err) throw err

                            var Rally = require('./Rally.js');
                            Rally.RallyWebAPI(path.resolve(__dirname,'./../../../Reports/json_report/jasmineRally.json'), function () {
                                deferred.fulfill()
                                wroteFile = true;
                            });
                        });
                    });
                });
            });
            return deferred;
        }
    };