/* author: jdalbey    date: 4/10/2019 */

// Parse the entire Incident XML Script file 
// Extract the Incidents and Events and create lists of each
function parseXml(response)
{
    // Create a parser and grab the high level tag we're interested in
    var parser = new DOMParser();
    var xmlDoc = parser.parseFromString(response,"text/xml");
    var eventTags = xmlDoc.getElementsByTagName("SCRIPT_EVENT");
    console.log("parsing incident xml file");
    // Process each SCRIPT_EVENT tag
    for (var i = 0; i < eventTags.length; i++)
    {
        var currEvt = eventTags[i];
        // local variable declarations
        var timeFields; var evtTime; var incidentNum; var incidentTitle; var cadProp; var telProp;
        var proparray = new Array();
        var evalarray = new Array();
        // Process all the children of one event
        for (var child = 1; child < currEvt.childNodes.length; child++)
        {
            // Ignore undefined nodes
            if (currEvt.childNodes[child].localName != undefined)
            {
                // Determine the tag type and dispatch it for further processing
                switch(currEvt.childNodes[child].localName)
                {
                    case "TIME_INDEX": 
                        timeFields = currEvt.childNodes[child].textContent.split(":"); 
                        evtTime = new Time(Number(timeFields[0]), Number(timeFields[1]), Number(timeFields[2]));
                        break;
                    case "INCIDENT":
                        incidentNum = Number(currEvt.childNodes[child].attributes["LogNum"].value);
                        incidentTitle =  currEvt.childNodes[child].textContent;
                        break;
                    case "GENERAL_INFO":  
                        /* This tag identifies a new incident.  As long as it appears before any
                        other tags, we can use it to create a new incident. (The alternative is to
                        have a separate function that parses xml to extract incidents before
                        we load events.)  Creating an event (below) requires that the incident has already
                        been created. */
                        var desc = currEvt.childNodes[child].getElementsByTagName("TEXT")[0].textContent;
                        var theIncident = new Incident(evtTime, incidentNum, incidentTitle, desc);
                        incidents.add(theIncident);
                        break;
                    case "CAD_DATA": 
                        var caddata = parseCAD(currEvt.childNodes[child]); 
                        if (caddata.length > 0)
                        {
                            cadProp = new Property("CHP CAD", caddata ); 
                            proparray.push(cadProp);
                        }
                        break;
                    case "TELEPHONE": 
                        telProp = new Evaluation("Telephone Conversation", 
                                 parseTelephone(currEvt.childNodes[child]) );  
                        evalarray.push(telProp);
                        break;
                    case "CHP_RADIO": 
                        var chpradio = parseCHPradio(currEvt.childNodes[child]); 
                        if (chpradio.length > 0)
                        {
                            cadProp = new Property("CHP RADIO", chpradio ); 
                            proparray.push(cadProp);
                        }
                        break;
                    case "TMT_RADIO":  break;
                    case "MAINTENANCE_RADIO": break;
                    // case *_EVALUATION: break;

                }
            }
        }
        //console.log(evtTime.format(), incidentNum, proparray.length, evalarray.length);
        // Ignore Media Log incident and empty nodes
        if (incidentNum != undefined && incidentNum != 100)
        {
          // Create new event with fields obtained from xml file
          events.add(new Event(evtTime, incidents.get(incidentNum), 
                new Properties(proparray), 
                new Evaluations(evalarray)) );
        }
    }
}

function parseCAD(element)
{
    var result = new Array();
    var details = element.getElementsByTagName("DETAIL");
    if (details.length > 0)
    {
        for (detail in details)
        {
            if (details[detail].textContent != undefined)
            {                
                result.push("Detail:");
                result.push(details[detail].textContent);
            }
        }
    }
    return result;
}
function parseTelephone(element)
{
    var result = new Array();
    for (var child = 1; child < element.childNodes.length; child++)
    {
        if (element.childNodes[child].localName != undefined)
        {
            if (element.childNodes[child].localName == "INSTRUCTOR")
            {
                result.push(element.childNodes[child].attributes["Role"].value);
            }
            else
            {
                result.push(element.childNodes[child].localName);   
            }
            result.push(element.childNodes[child].textContent);
        }
    }
    return result;
}
function parseCHPradio(element)
{
    var result = new Array();
    var dialog = element.getElementsByTagName("LINE");
    if (dialog.length > 0)
    {
        for (line in dialog)
        {
            if (dialog[line].textContent != undefined)
            {                
                result.push(dialog[line].attributes["Role"].value);
                result.push(dialog[line].textContent);
            }
        }
    }
    return result;
}

// MAIN
console.log("starting LoadEvents");
try {
    // the script must be located where accessible by the web server
    var scriptFilename = "incident_script.xml";
    console.log("Attempting to load", scriptFilename);
    // Now load the Incident Script and go parse it
    loadJSON(scriptFilename, parseXml)

    } catch(e) {
        console.log("Error attempt to parse incident script "+response)
    }


