$(document).ready(function () {
  var token = document.body.getAttribute('data-token');

  function renderHtmlAndGetText(stringValue) {
    var div = document.createElement('div');
    div.innerHTML = stringValue;
    return div.textContent;
  }

  function isJson(stringValue) {
    var json;
    try {
      json = JSON.parse(stringValue);
    } catch (e) {
      return false;
    }
    return typeof json === 'object';
  }

  function parseValidJson(stringValue) {
    var json;
    try {
      json = JSON.parse(stringValue);
    } catch (e) {
      return false;
    }
    return (typeof json === 'object') ? json : false;
  }

  $(document).on('click', '.js-error-filter', function () {
    var data = {};
    var type_error = $("select[name='filter_error_type']").val();
    data['type_error'] = type_error;

    $.ajax({
      url: 'index.php?route=module/skyhub/error/getErrors&token=' + token,
      type: 'get',
      data: data,
      dataType: 'json',
      beforeSend: function () {
        $('body').append(loadBeforeSend());
      },
      complete: function () {
        $('.loadBeforeSend').fadeOut();
      },
      success: function (json) {
        function addZero(i) {
          if (i < 10) {
            i = "0" + i;
          }
          return i;
        }

        var entity_id = '';
        var entity_link = '';
        var error_category_code = '';
        var data = '';
        var hora = '';
        var errorMessage = '';
        var errorObject = '';
        var errorArray = '';

        var html = '';
        html += '<div class="content-box js-div-results">';

        $('.js-div-results').remove();

        if (json['errors_qty'] > 0) {
          $.each(json['data'], function (index, value) {
            entity_id = value['entity_id'];
            entity_link = value['link'] ? 'href="' + value['link'] + '"' : '';

            $.each(value['categories'], function (ind, val) {
              error_category_code = val['error_category_code'];
              $.each(val['errors'], function (i, v) {
                errorObject = parseValidJson(v['message']);

                if (errorObject){
                  errorMessage = errorObject.message;
                  errorArray = errorObject.errors;
                } else {
                  errorMessage = renderHtmlAndGetText(v['message']);
                  errorArray = false;
                }

                html += '<a ' + entity_link + ' class="content-box visible-block text-decoration-none">';
                html += '<div class="row no-space-xs middle-xs top-padding-medium horizontal-padding-medium ' +
                  'background-white shadow-small hover:shadow-large bottom-margin-small">';
                html += '<div class="col-md-1 col-xs-12">';
                html += '<div class="content-box bottom-padding-medium">';
                html += '<span class="text-small text-dark text-bold">' + '#' + entity_id + '</span>';
                html += '</div>';
                html += '</div>';
                html += '<div class="col-md-10 col-xs-12">';
                html += '<div class="content-box bottom-padding-medium">';

                html += '<span class="text-small text-gray text-word-wrap">' + errorMessage + '</span>';
                html += '</div>';
                if (errorArray) {
                  html += '<div class="content-box bottom-padding-medium">';
                  $.each(errorArray, function (idx, valor) {
                    html += '<span class="text-small text-dark visible-block">' + valor + ' </span>';
                  });
                  html += '</div>';
                }
                html += '</div>';
                html += '<div class="col-md-1 col-xs-12">';
                html += '<div class="content-box bottom-padding-medium">';
                data = new Date(v['last_occurrence']);
                hora = addZero(data.getHours()) + ':' + addZero(data.getMinutes()) + ':' + addZero(data.getSeconds());
                data = addZero(data.getDate()) + '/' + addZero(data.getMonth()+1) + '/' + data.getFullYear();
                html += '<span class="text-small text-dark text-center visible-block">' + hora + '</span>';
                html += '<span class="text-small text-dark text-center visible-block">' + data + '</span>';
                html += '</div>';
                html += '</div>';
                html += '</div>';
                html += '</a>';
              });
            });
          });
        } else {
          html += '<div class="row">';
          html += '<div class="col-xs-12">';
          html +=
            '<div class="content-box background-white shadow-small vertical-padding-x-large horizontal-padding-large text-center">';
          html += '<span class="text-medium text-gray">Nenhum erro encontrado!</span>';
          html += '</div>';
          html += '</div>';
          html += '</div>';
        }

        html += '</div>';
        html += '</div>';

        $('.errors').append(html);

      },
      error: function (xhr, ajaxOptions, thrownError) {
        console.log(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
      },
    });
  });
})
