function showError(msg) {
  $('#loading').hide();
  $('#ListContainer').empty();
  $('#ListContainer').append("<ul><li><span class='entry text-bg-danger'>" + msg + "</span></li></ul>");
}

function testAborted() {
  $('#Summary').html("<span class='text-bg-danger'>This test was ABORTED</span><br/><br/><br/>");
  $('#Summary').show();
}

String.prototype.capitalize = function () {
  return this.charAt(0).toUpperCase() + this.slice(1);
}

jQuery.expr[':'].regex = function (elem, index, match) {
  var matchParams = match[3].split(','),
    validLabels = /^(data|css):/,
    attr = {
      method: matchParams[0].match(validLabels) ?
        matchParams[0].split(':')[0] : 'attr',
      property: matchParams.shift().replace(validLabels, '')
    },
    regexFlags = 'ig',
    regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g, ''), regexFlags);
  return regex.test(jQuery(elem)[attr.method](attr.property));
}

function isTestAttribute(str) {
  var regex = /^@\?_#\$\$(\w+)\$\~(.*)/g;
  var match = regex.exec(str);
  return match != null;
}

function testAttributeName(str) {
  var regex = /^@\?_#\$\$(\w+)\$\~(.*)/g;
  var match = regex.exec(str);
  var attrName = match[1];
  return attrName;
}

function testAttributeValue(str) {
  var regex = /^@\?_#\$\$(\w+)\$\~(.*)/g;
  var match = regex.exec(str);
  var attrValue = match[2];
  return attrValue;
}

var is_aborted = false;

function xmlParser(xml, parent) {
  var successful = true;
  $(xml).contents().each(function (i, el) {
    var nodename = el.nodeName.toUpperCase();
    if (nodename == "TESTLOG") {
      var ul = $('<ul class="treeview">').appendTo(parent);
      xmlParser($(el), ul);
    } else
      if (nodename == "TESTSUITE") {
        var li = $('<li>').html("<span class='suite'>Suite: " + $(el).attr('name') + "</span>").appendTo(parent);

        if ($(el).attr('skipped') != 'yes') {
          var c = $('<ul>').appendTo(li);
          var succ = xmlParser($(el), c);
          if (succ) {
            li.children('span').first().addClass('text-bg-success');
          } else {
            li.children('span').first().addClass('text-bg-danger');
          }

          successful = succ && successful;
        } else {
          li.children('span').first().addClass('text-bg-secondary');
          li.addClass('skipped');
        }
      } else
        if (nodename == "TESTCASE") {
          var li = $("<li class='closed'>").html("<span class='case'>Case: " + $(el).attr('name') + "</span>").appendTo(parent);
          //c attributumok feldolgozasa
          var div = $('<div style="padding: 1rem 1rem 0rem 1rem;">').addClass('boxshadow');
          $(el).children("Message").each(function (i, msg) {
            var txt = $(msg).text();
            if (isTestAttribute(txt)) {
              var attrName = testAttributeName(txt);
              var attrValue = testAttributeValue(txt);
              var tag = "<b>" + attrName + ": </b>" + attrValue;
              div.append($('<p>').html(tag));
            }
          });

          var c = $('<ul>').appendTo(li);
          if ($(div).children().length > 0) {
            div.appendTo(c);
          }

          var succ = xmlParser($(el), c);
          if (succ) {
            li.children('span').first().addClass('text-bg-success');
          } else {
            li.children('span').first().addClass('text-bg-danger');
          }
          successful = succ && successful;
        } else
          if (nodename == "INFO") {
            var li = $('<li>').html("<span class='entry text-bg-success'>" + $(el).text() + "</span>").appendTo(parent);

            successful = true && successful;
          } else
            if (nodename == "ERROR" || nodename == "EXCEPTION") {
              var li = $('<li>').html("<span class='entry text-bg-danger'>" + $(el).text() + "</span>").appendTo(parent);
              li.attr('data-jstree', '{"icon":"images/error.png"}');

              var file = "<b>File: </b>" + $(el).attr('file');
              var line = "<b>Line: </b>" + $(el).attr('line');
              var div = $('<div style="padding: 1rem 1rem 0rem 1rem;">').addClass('boxshadow').appendTo(li);
              div.append($('<p>').html(line)).append($('<p>').html(file));

              successful = false && successful;
            } else
              if (nodename == "MESSAGE") {
                var txt = $(el).text();
                if (txt == 'Test is aborted') {
                  is_aborted = true;
                }
                if (!isTestAttribute(txt)) {
                  var li = $('<li>').html("<span class='entry text-bg-warning'>" + txt + "</span>").appendTo(parent);
                }
              }

  });
  return successful;
}

function createTreeView() {
  $('#ListContainer>ul').treeview({
    animated: "normal",
    collapsed: false
  });
}

function prepareDisplay() {
  $('#ListContainer').empty();
  $('#loading').show();

  $('#Summary').hide();
  $('#Summary').html("");
}

function showResultXml(xml) {
  showResult(function (display) {
    display(xml);
  });
}

function showResult() {
  prepareDisplay();

  let id = $('#test_id').val();

  $.ajax({
    url: 'https://www.archline.hu/maintenance/tests/get_xml.php?id=' + id,
    contentType: "application/x-www-form-urlencoded;charset=UTF-8",
    cache: false
  }).done(function (xml) {
    var parseXml;

    if (window.DOMParser) {
      parseXml = function (xmlStr) {
        return (new window.DOMParser()).parseFromString(xmlStr, "text/xml");
      };
    } else if (typeof window.ActiveXObject != "undefined" && new window.ActiveXObject("Microsoft.XMLDOM")) {
      parseXml = function (xmlStr) {
        var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xmlStr);
        return xmlDoc;
      };
    } else {
      parseXml = function () { return null; }
    }

    var xmlDoc = parseXml(xml);

    xmlParser(xmlDoc, $('#ListContainer'));
    createTreeView();
    $('#loading').hide();
  }).fail(function (jqXHR, textStatus, errorThrown) {
    showError("No test result was generated due to build system failure.");
  });
}

$(function () {
  $("body").on("drop", function (e) {
    console.log(e);
  });

  showResult();
});