//RC-all START
//замена тегов html
function encodeHtmlspecialchars($str){
    var $map =
    {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
    };
    //return $str
    return $str.toString().replace(/[&<>"']/g, function($m) {return $map[$m];});
}
//замена тегов html
function decodeHtmlspecialchars($str){
    var $map =
    {
        '&amp;': '&',
        '&lt;': '<',
        '&gt;': '>',
        '&quot;': '"',
        '&#039;': "'"
    };
    return $str.toString().replace(/&amp;|&lt;|&gt;|&quot;|&#039;/g, function($m) {return $map[$m];});
}
//отображение формы загрузки
function f_loaderVisible(){
  $table_area.html('');
  $table_area2.html('');
  $('#id_loader').show().html('<div class="loader"></div>');
}

//проверка залогинились ли
function f_isLogin(){
  if (global.config['loginform']['visible'] != false) {
    return false;
  }
  return true;
}
//RC-all END

//отображение формы логина
function f_loginFormVisibleElk(){
  var $login = '';
  var $autofocus_login = 'autofocus';
  var $autofocus_password = '';
  if(global.config['loginform']['login'] != undefined){
    $login = global.config['loginform']['login']
    if($login != ''){
      $autofocus_login = '';
      $autofocus_password = 'autofocus';
    }else{
      $autofocus_login = 'autofocus';
      $autofocus_password = '';
    }
    
    
  }
  $('#id_loader').hide();

  $table_area.html('<div class="container">\
  <div class="row">\
    <div class="col">\
    </div>\
    <div class="col">\
  <h2 class="form-signin-heading"><br><br><br>Please sign in</h2>\
  <label for="loginLogin" class="sr-only">Login</label>\
  <input type="text" id="loginLogin" class="form-control" placeholder="Login" required '+
      $autofocus_login+' value="'+$login+'">\
  <label for="loginPassword" class="sr-only">Password</label>\
  <input type="password" id="loginPassword" class="form-control" placeholder="Password" value=""'+
      $autofocus_password+' required>\
  <button class="btn btn-lg btn-primary btn-block" type="submit" id="loginButton">Sign in</button>\
    </div>\
    <div class="col">\
    </div>\
  </div>\
</div>');
//ввод пароля
  $('#loginPassword').keypress(function(event){
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if(keycode == '13'){
      global.config['loginform']['visible'] = false;
      global.config['loginform']['login'] =  $('#loginLogin').val();
      global.config['loginform']['password'] =  $('#loginPassword').val();
      $table_area.html('');
    }
    //Stop the event from propogation to other handlers
    //If this line will be removed, then keypress event handler attached
    //at document level will also be triggered
    event.stopPropagation();
  });
  $('#loginButton').click(function(){
    global.config['loginform']['visible'] = false;
    global.config['loginform']['login'] =  $('#loginLogin').val();
    global.config['loginform']['password'] =  $('#loginPassword').val();
    $table_area.html('');
  });
}

//инициализация поиска - сбор значений
function f_searchInitializationElk(){
  if(f_isLogin()){
		var $start_position = 0;
		f_getDataFromElk($start_position);
	}else{
		alert('Need LogIn');
	}
}

//поиск данных
function f_getDataFromElk($start_position){
  f_loaderVisible();
  var $reqest_data_app = '';
  var $url = global.config['url'];
  var $time_from = $("#time_from").val();
  var $time_to = $("#time_to").val();
  var $beat_name = $("#beat_name").val();
  var $application_type = $("#application_type").val();
  var $countPerPage = $("#countPerPage").val();
  var $app = $("#app").val();
  var $search_string = $("#search_string").val().replace(/\\/g, "\\\\").replace(/\"/g, '\\"');
  var $order = "desc";
  if($app != ""){
    if(typeof $app === 'object'){
      $app.forEach($app_name => {
        $reqest_data_app = $reqest_data_app + '{\
          "match_phrase": {\
            "'+global.config['keyname']['app']+'": "'+$app_name+'"\
          }\
        },';
      });
      $reqest_data_app = '{"bool": {\
        "should": [\
          '+$reqest_data_app.slice(0, -1)+'\
        ]\
      }},';
    }else{
      $reqest_data_app = '{\
        "match_phrase": {\
          "'+global.config['keyname']['app']+'": {\
            "query": "'+$app+'"\
          }\
        }\
      },';
    }
  }
  let $reqest_data_beat_name = '';
  if ($beat_name != ""){
    $reqest_data_beat_name = '{\
      "regexp": {\
        "beat.name": "'+$beat_name+'"\
      }\
    },';
  }
  let $reqest_data_application_type = '';
  if ($application_type != "Application type"){
    $reqest_data_application_type = '{\
      "match_phrase": {\
        "'+global.config['keyname']['application_type']+'": {\
          "query": "'+$application_type+'"\
        }\
      }\
    },';
  }
  let $reqest_data_time_from = '';
  let $reqest_data_time_to = '';
  if ($time_from != ""){
    $reqest_data_time_from = '"gte": "'+$time_from+'", ';
  }
  if ($time_to != ""){
    $reqest_data_time_to = '"lte": "'+$time_to+'", ';
  }
  let $reqest_data_search_string = '';
  if ($search_string != ""){
    $reqest_data_search_string= '{\
      "query_string": {\
        "query": "'+$search_string+'",\
        "analyze_wildcard": true\
      }\
    },';
  }
  
  let $reqest_data = '{\
  "version": true,\
  "query": {\
    "bool": {\
      "must": [\
        '+$reqest_data_search_string+'\
        '+$reqest_data_app+'\
        '+$reqest_data_beat_name+'\
        '+$reqest_data_application_type+'\
        {\
          "range": {\
            "@timestamp": {\
              '+$reqest_data_time_from+'\
              '+$reqest_data_time_to+'\
              "time_zone": "+03:00"\
            }\
          }\
        }\
      ]\
    }\
  },\
  "from": '+$start_position+',\
  "size": '+$countPerPage+',\
  "sort": [\
    {\
      "@timestamp": {\
        "order": "'+$order+'",\
        "unmapped_type": "boolean"\
      }\
    }\
  ]\
  }';
    if(global.config['debug']){
      console.log($reqest_data);
    }
  $.ajax
  ({
    type: "POST",
    url: $url,
    dataType: 'json',
    async: true,
    headers: {
      "Authorization": "Basic " + btoa(global.config['loginform']['login'] + ":" + global.config['loginform']['password'])
    },
    data: $reqest_data,
    success: function ($req){
      var $total = $req['hits']['total'];
        if(global.config['debug']){
          //логирование ответа
          console.log($req);
          console.log('total: '+$total);
        }
      $table_area.html('Data received. Processing of results.');
      global.responseRaw = '';
      //проверка на мультивыбор APP. Если выбрано несколько и у них равное количество столбцов, показывается с настройками из конфига
      //если колчичество столбцов разное у выбранных тегов, то отбражается по дефолту - одно поле message
      if(typeof $app === 'object'){
        if(Object.keys($app).length == 0){
          global.$columncount = -1;
        }else{
          global.$columncount = 0;
        }
        $app.forEach($app_name => {
          var $columncount = Object.keys(global.config['tableview'][$app_name]['rows']['0']['columns']).length;
          if(global.$columncount == 0){
            global.$columncount = $columncount
          }else{
            if(global.$columncount != $columncount && global.$columncount != -1){
              global.$columncount = -1;
            }
          }
        });
        if(global.$columncount == -1){
          $app = '@ERROR@';
        }else{
          $app = $app[0];
        }
      }
      var $div_body = f_table_header($app);

      var $table_body = '';
      var $table_footer = '\
        </tbody></table>';
      global.$req = $req['hits']['hits'];
      for (var $key in $req['hits']['hits'] ) {
        $table_body = $table_body + f_table_body($app, $req, $key);
      }
      $table_area.html( $div_body + $table_body + $table_footer);
      if($total == '0'){
        $table_area.html('not found anything');
      }else{
        var $pagesCount = Math.ceil($total/$countPerPage);
        var $pageCurrent = Math.ceil($start_position/$countPerPage)+1;

        var $navigationText = '';
        if($pageCurrent == 1){
          $navigationText = '<li class="page-item disabled"><a class="page-link" href="#">Previous</a></li>';
        }else{
          $start_position = parseInt($countPerPage)*parseInt($pageCurrent) - parseInt($countPerPage)*2;
          $navigationText = '<li class="page-item"><a class="page-link" href="#" \
          onClick=\'f_getDataFromElk("'+$start_position+'");\' \
          >Previous</a></li>';
        }
        
        if($pagesCount >= 11){
          if($pagesCount - $pageCurrent > 5){
            if($pageCurrent <= 5){
              for (var $i = 1; $i <= $pageCurrent + 5; $i++) {
                if($i == $pageCurrent){
                  $navigationText =  $navigationText + '<li class="page-item active"><a class="page-link" href="#">'+$i+'</a></li>';
                }else{
                  $start_position = (parseInt($i)-1)*parseInt($countPerPage);
                  $navigationText =  $navigationText + '<li class="page-item"><a class="page-link" href="#" \
                  onClick=\'f_getDataFromElk("'+$start_position+'");\' \
                  >'+$i+'</a></li>';
                }
              }
            }else{
              for (var $i = $pageCurrent - 5; $i <= $pageCurrent + 5; $i++) {
                if($i == $pageCurrent){
                  $navigationText =  $navigationText + '<li class="page-item active"><a class="page-link" href="#">'+$i+'</a></li>';
                }else{
                  $start_position = (parseInt($i)-1)*parseInt($countPerPage);
                  $navigationText =  $navigationText + '<li class="page-item"><a class="page-link" href="#" \
                  onClick=\'f_getDataFromElk("'+$start_position+'");\' \
                  >'+$i+'</a></li>';
                }
              }
            }
          }else{
            for (var $i = $pagesCount - 5; $i <= $pagesCount; $i++) {
              if($i == $pageCurrent){
                $navigationText =  $navigationText + '<li class="page-item active"><a class="page-link" href="#">'+$i+'</a></li>';
              }else{
                $start_position = (parseInt($i)-1)*parseInt($countPerPage);
                $navigationText =  $navigationText + '<li class="page-item"><a class="page-link" href="#" \
                onClick=\'f_getDataFromElk("'+$start_position+'");\' \
                >'+$i+'</a></li>';
              }
            }
          }
        }else{
          for (var $i = 1; $i <= $pagesCount; $i++) {
            if($i == $pageCurrent){
              $navigationText =  $navigationText + '<li class="page-item active"><a class="page-link" href="#">'+$i+'</a></li>';
            }else{
              $start_position = (parseInt($i)-1)*parseInt($countPerPage);
              $navigationText =  $navigationText + '<li class="page-item"><a class="page-link" href="#" \
                onClick=\'f_getDataFromElk("'+$start_position+'");\' \
                >'+$i+'</a></li>';
            }
          }
        }
        if($pageCurrent == $i-1){
          $navigationText = $navigationText + '<li class="page-item disabled"><a class="page-link" href="#">Next</a></li>';
        }else{
          $start_position = parseInt($countPerPage)*parseInt($pageCurrent);
          $navigationText = $navigationText + '<li class="page-item"><a class="page-link" href="#" \
            onClick=\'f_getDataFromElk("'+$start_position+'");\' \
            >Next</a></li>';
        }

        $table_area.append('\
        <nav aria-label="Page navigation">\
        <ul class="pagination">\
          '+$navigationText+'\
        </ul>\
      </nav>\
        ');
      }
      $('#id_loader').hide().html('');
    },
    error: function($resp, $exception, $error){
      switch ($resp.status) {
        case 401:
          $error = $error + '\n\r The username or password is incorrect';
          f_loginFormVisibleElk();
          break;
        case 403:
          $error = $error + '\n\r Access is denied';
          $table_area.html($resp.status+': '+$error);
          break;
        case 500:
          $error = $error + '\n\r Server error';
          $table_area.html($resp.status+': '+$error);
          break;
      }
      $('#id_loader').hide();
      alert($resp.status+': '+$error);
    }
  });
}

function f_clipboard_elk(){
  var $selectedText = "";
    if (window.getSelection){ // all modern browsers and IE9+
        $selectedText = window.getSelection().toString();
        clipboard.writeText($selectedText);
    }
}

//отрисовка таблицы
function f_table_header($app){
  try {
    var $objConfigTableviewRows = global.config['tableview'][$app]['rows'];
    var $table_row = "";
    var $table_row_class = "";
    Object.keys($objConfigTableviewRows['0']['columns']).forEach($column => {
      $table_row_class = '';
      if($objConfigTableviewRows['0']['columns'][$column]["tableclass"]){
        $table_row_class = ' class="'+$objConfigTableviewRows['0']['columns'][$column]["tableclass"]+'"';
      };
      if($objConfigTableviewRows['0']['columns'][$column]["name"]){
        $column = $objConfigTableviewRows['0']['columns'][$column]['name'];
      };
      $table_row = $table_row + '<th scope="col" ' + $table_row_class + '>' + $column + '</th>';
    });
    var $div_body = '\
          <table class="table-output table table-bordered table-striped table-hover table-sm responsive-table">\
            <thead>\
              <tr class="d-flex">\
                ' + $table_row + '\
              </tr>\
            </thead>\
            <tbody>';
    
  }catch($e){
    var $div_body = '\
          <table class="table-output table table-bordered table-striped table-hover table-sm responsive-table">\
            <thead>\
              <tr class="d-flex">\
                <th scope="col">Message</th>\
              </tr>\
            </thead>\
            <tbody>';
  }

  return $div_body;
}

//получение значени объекта из конфига
function objpath($obj, $path) {
  try {
    $path = $path.replace(/^\[[\'\"]/, '');
    $path = $path.replace(/[\'\"]\]$/, '');
    $path = $path.replace(/[\'\"]\]\[[\'\"]/g, '.');
    return $path.split('.').reduce(function($prev, $curr) {
      return $prev ? $prev[$curr] : null
    }, $obj || self)
  }catch($e) {
     return undefined;
  }
}

//отрисовка таблицы
function f_table_body($app, $req, $key){
  var $table_body = '';
  var $tr_class = "";
  var $table_body_tr0 = "";
  var $table_body_tr = "";
  var $numColumns = 0;
  if($app != '@ERROR@'){
    try{
      $app = $req['hits']['hits'][$key]['_source']['app']
    }catch($e) {};
  }
  try{
    var $objConfigTableviewRows = global.config['tableview'][$app]['rows'];
    Object.keys($objConfigTableviewRows).forEach($row => {
      if($row == 0){//первая строка
        Object.keys($objConfigTableviewRows[$row]['columns']).forEach($column => {
          $table_row_class = '';
          if($objConfigTableviewRows[$row]['columns'][$column]["tableclass"]){
            $table_row_class = ' class="'+$objConfigTableviewRows[$row]['columns'][$column]["tableclass"]+'"';
          };
          switch ($objConfigTableviewRows[$row]['columns'][$column]["type"]) {
            case "json":
              var $jsondata = objpath($req['hits']['hits'][$key], $objConfigTableviewRows[$row]['columns'][$column]['jsondata']);
              if($jsondata == undefined){
                $jsondata = $req['hits']['hits'][$key]['_source']['json']['json_error'];
                if($jsondata == undefined){
                  $jsondata = '';
                }else{
                  $jsondata = "ERROR: "+$jsondata;
                }
              }
              if($jsondata == undefined){
                $jsondata = '';
              }
              $table_body_tr0 = $table_body_tr0 + '\
                  <td'+$table_row_class+'><pre>'+encodeHtmlspecialchars($jsondata)+'</pre></td>';
            break;
            case "regexp":
              var $regexp = new RegExp($objConfigTableviewRows[$row]['columns'][$column]['regexpdata']);
              var $jsondata = objpath($req['hits']['hits'][$key], $objConfigTableviewRows[$row]['columns'][$column]['jsondata']);
              if($jsondata == undefined){
                $jsondata = '';
              }else{
                $jsondata = $jsondata.match($regexp);
                try {
                  $jsondata = $jsondata[1];
                }catch(e) {
                  $jsondata = '';
                }
              }
              $table_body_tr0 = $table_body_tr0 + '\
              <td'+$table_row_class+'><pre>'+encodeHtmlspecialchars($jsondata)+'</pre></td>';
            break;
          }
          $numColumns = $numColumns + 1;
          //цвет строки
          if($column == "State" || $column == "Status"){
            $tr_class = '';
            switch ($jsondata.toString()) {
              case "WARN":
                if(global.$tr_class_old == "table-danger_new"){
                  $tr_class = 'table-danger_new2';
                }else{
                  $tr_class = 'table-danger_new';
                }
                break;
              case "INFO":
                if(global.$tr_class_old == "table-info_new"){
                  $tr_class = 'table-info_new2';
                }else{
                  $tr_class = 'table-info_new';
                }
                break;
              case "DEBUG":
                if(global.$tr_class_old == "table-debug_new"){
                  $tr_class = 'table-debug_new2';
                }else{
                  $tr_class = 'table-debug_new';
                }
                break;
              case "ERROR":
                if(global.$tr_class_old == "table-warning_new"){
                  $tr_class = 'table-warning_new2';
                }else{
                  $tr_class = 'table-warning_new';
                }
                break;
              case "200":
                if(global.$tr_class_old == "table-success_new"){
                  $tr_class = 'table-success_new2';
                }else{
                  $tr_class = 'table-success_new';
                }
                break;
              case "404":
                if(global.$tr_class_old == "table-danger_new"){
                  $tr_class = 'table-danger_new2';
                }else{
                  $tr_class = 'table-danger_new';
                }
                break;
              case "500":
                if(global.$tr_class_old == "table-danger_new"){
                  $tr_class = 'table-danger_new2';
                }else{
                  $tr_class = 'table-danger_new';
                }
                break;
            }
            global.$tr_class_old = $tr_class;
          }
        });
      }else{//вторая и последующие строки
        var $jsondata_all = '';
        Object.keys($objConfigTableviewRows[$row]['columns']).forEach($column => {
          switch ($objConfigTableviewRows[$row]['columns'][$column]["type"]) {
            case "json":
              var $jsondata = objpath($req['hits']['hits'][$key], $objConfigTableviewRows[$row]['columns'][$column]['jsondata']);
              if($jsondata == undefined){
                $jsondata = $req['hits']['hits'][$key]['_source']['json']['json_error'];
                if($jsondata == undefined){
                  $jsondata = '';
                }else{
                  $jsondata = "ERROR: "+$jsondata;
                }
              }
              if($jsondata == undefined){
                $jsondata = '';
              }
              
              $jsondata_all = ($jsondata_all + '\n\r' + $jsondata).trim();
            break;
            case "regexp":
              var $regexp = new RegExp($objConfigTableviewRows[$row]['columns'][$column]['regexpdata']);
              var $jsondata = objpath($req['hits']['hits'][$key], $objConfigTableviewRows[$row]['columns'][$column]['jsondata']);
              if($jsondata == undefined){
                $jsondata = '';
              }else{
                $jsondata = $jsondata.match($regexp);
                try {
                  $jsondata = $jsondata[1];
                }catch(e) {
                  $jsondata = '';
                }
              }
              $jsondata_all = ($jsondata_all + '\n\r' + $jsondata).trim();
            break;
          }
        });
      $table_body_tr = $table_body_tr + '\
      <tr>\
        <td colspan="'+$numColumns+'"><pre>'+ encodeHtmlspecialchars($jsondata_all)+'</pre></td>\
      </tr>';
      }
      
    });
    }catch($e) {//если индекса нет в кофиге
    var $table_body_tr0 = global.$req[$key]['_source']['message'];
    if($table_body_tr0 == undefined){
      $table_body_tr0 = '';
      Object.keys(objpath(global.$req[$key], "['_source']['json']")).forEach($jsondata_name => {
        var $jsondata = objpath(global.$req[$key], "['_source']['json']"+'[\''+$jsondata_name+'\']');
        if($jsondata == undefined){
          $jsondata = '';
        }else if(typeof $jsondata === 'object'){
          var $jsondata_temp = '';
          Object.keys($jsondata).forEach($jsondata_name => {
            if(typeof $jsondata[$jsondata_name] != 'object'){
              $jsondata_temp = ($jsondata_temp + ' ' + $jsondata[$jsondata_name]).trim();
            }
          });
          $jsondata = $jsondata_temp;
        }
        $table_body_tr0 = ($table_body_tr0 + " " + $jsondata).trim();
      });
      if($table_body_tr0 == ''){
        $table_body_tr0 = 'ERROR: not found';
      }
    }
    var $req_beat_name = $req['hits']['hits'][$key]['_source']['beat']['hostname'];
    $table_body_tr0 = '<td '+$tr_class+'><pre>'+ encodeHtmlspecialchars($req_beat_name+' - '+$table_body_tr0)+'</pre></td>';
    $tr_class = '';
    $table_body_tr = '';
   }

  $table_body = '\
    <tr class="d-flex '+$tr_class+'">\
      '+$table_body_tr0+'\
    </tr>\
    '+$table_body_tr;

  return $table_body;
}

//получение текста для копирования в буфер
function f_rawdata(){
  $('#id_loader').show().html('<div class="loader"></div>');
  var $responseRaw ='';
    for (var $key in global.$req) {
      var $responseRaw_single = "";
      try{//проверка наличия конфига
        var $app = objpath(global.$req[$key], "['_source']['app']")
        var $objConfigTableviewRaw = global.config['tableview'][$app]['raw'];
        switch ($objConfigTableviewRaw["type"]) {
          case "json_single":
            var $jsondata = objpath(global.$req[$key], $objConfigTableviewRaw["jsondata"]);
            if($jsondata == undefined){$jsondata = '';};
            $responseRaw_single = $jsondata;
          break;
          case "json_all":
              Object.keys(objpath(global.$req[$key], $objConfigTableviewRaw["jsondata"])).forEach($jsondata_name => {
                var $jsondata = objpath(global.$req[$key], $objConfigTableviewRaw["jsondata"]+'[\''+$jsondata_name+'\']');
                if($jsondata == undefined){
                  $jsondata = '';
                }else if(typeof $jsondata === 'object'){
                  var $jsondata_temp = '';
                  Object.keys($jsondata).forEach($jsondata_name => {
                    if(typeof $jsondata[$jsondata_name] != 'object'){
                      $jsondata_temp = ($jsondata_temp + ' ' + $jsondata[$jsondata_name]).trim();
                    }
                  });
                  $jsondata = $jsondata_temp;
                }
                $responseRaw_single = ($responseRaw_single + " " + $jsondata).trim();
              });
          break;
        }
      }catch($e){//конфиг не найден - попытка найти без него
        var $responseRaw_single = global.$req[$key]['_source']['message'];
        if($responseRaw_single == undefined){
          $responseRaw_single = '';
          Object.keys(objpath(global.$req[$key], "['_source']['json']")).forEach($jsondata_name => {
            var $jsondata = objpath(global.$req[$key], "['_source']['json']"+'[\''+$jsondata_name+'\']');
            $responseRaw_single = ($responseRaw_single + " " + $jsondata).trim();
          });
          if($responseRaw_single == ''){
            $responseRaw_single = 'ERROR: not found';
          }
        }
      }
      $responseRaw = ($responseRaw + '\r\n' + $responseRaw_single).trim();
    }
  $('#id_loader').hide();
  return $responseRaw;
}

//копирование исходного текста в буфер
function f_clipboardrawdata(){
  //показываем загрузку
  $('#id_loader').show().html('<div class="loader"></div>');
  //устанавливаем sleep для отображения загрузки
  setTimeout(function (){
  clipboard.writeText(f_rawdata());
  $('#id_loader').hide();
  }, 50);
}