var data;

function SettParams() {
  var json = JSON.parse($("#jsonTest").val());
  json.app_option = $("#text3").val();
  json.username = $("#text4").val();
  json.password = $("#text5").val();
  $("#jsonTest").val(JSON.stringify(json, null, 4));
}

function Reset() {
  var json = JSON.parse($("#jsonTest").val());
  json.data = "";
  $("#jsonTest").val(JSON.stringify(json, null, 4));
  $("#paramsList").html("");
}

function ShowDataResponse() {
  var json = JSON.parse(document.getElementById("test").innerHTML);

  if (json.data !== undefined && json.data !== "") {
    document.getElementById("showData").innerHTML = JSON.stringify(JSON.parse(json.data), null, 2);
    $('#dataModal').modal('show');
  }
};

function ShowDataRequest() {
  var json = JSON.parse(document.getElementById("upit").innerHTML);

  if (json.data !== undefined && json.data !== "") {
    document.getElementById("showData").innerHTML = JSON.stringify(JSON.parse(json.data), null, 2);
    $('#dataModal').modal('show');
  }
};

function DodajParametar() {
  var json = JSON.parse($("#jsonTest").val());
  if (json.data != "") {
    data = JSON.parse(json.data);
  } else {
    data = {};
  }
  data[$("#text1").val()] = $("#text2").val();
  $("#paramsList").append(
    "<ul>" + $("#text1").val() + ":" + $("#text2").val() + "</ul>"
  );
  json.data = JSON.stringify(data);
  $("#jsonTest").val(JSON.stringify(json, null, 4));
}

var mResponse;

$(function () {
  $("[data-toggle='tooltip']").tooltip();
});

$(document).ready(function () {
  $("#loader").removeClass("spinner-border");

  $("#okButton").click(function () {
    $("#loader").addClass("spinner-border");

    var array = JSON.parse($("#jsonTest").val());
    if (document.getElementById("changeReqId").checked) {
      array.req_id = Math.random().toString(36).substr(2, 14);
    }

    $("#jsonTest").val(JSON.stringify(array, null, 4));
    array = JSON.parse($("#jsonTest").val());

    if (document.getElementById("changeChecksum").checked) {
      array.checksum = md5(array.data + array.req_id + $("#pk").val());
      $("#checksum").html(array.checksum);
    } else {
      $("#checksum").html("");
    }
    var DebugLevel = $("#textboxDebugLevel").val();
    var DebugSection = $("#textboxDebugSection").val();
    var APIVersion = $("#textboxAPIVersion").val();

    const Url = "/InfoAPI.aspx";
    const Data = $.param({
      json: JSON.stringify(array),
      DebugLevel: DebugLevel,
      DebugSection: DebugSection,
      APIVersion: APIVersion,
    });
    const Param = {
      headers: {
        "content-type": "application/x-www-form-urlencoded",
      },
      body: Data,
      method: "POST",
    };

    document.getElementById("upit").innerHTML = JSON.stringify(array, undefined, 2);

    let start = +new Date();
    window
      .fetch(Url, Param)
      .then(function (data) {
        document.getElementById("databaseattachmentJson").innerHTML = "";

        let ct = data.headers.get("content-type");
        if (ct.indexOf("json") > -1)
          return new Promise(function (resolve) {
            data.json().then(function (res) {
              resolve({ type: 1, data: res });
            });
          });
        if (ct.indexOf("text") > -1)
          return new Promise(function (resolve) {
            data.text().then(function (res) {
              resolve({ type: 3, data: res });
            });
          });

        var ext = data.headers.get("x-extension") || "";
        return new Promise(function (resolve) {
          data.blob().then(function (res) {
            resolve({ type: 2, data: res, ext: ext });
          });
        });
      })
      .then(function (res) {
        let end = +new Date();
        let diff = end - start;
        $("#vreme").html(diff + " milisekundi.");

        switch (res.type) {
          case 1:
            $("#debugLog").html(res.data.debug_log);
            delete res.data.debug_log;

            document.getElementById("test").innerHTML = JSON.stringify(
              res.data,
              undefined,
              2
            );

            document.getElementById(
              "databaseattachmentJson"
            ).innerHTML = JSON.stringify(
              JSON.parse(JSON.parse(res.data.data).databaseattachment),
              undefined,
              2
            );
            break;
          case 2:
            var filename = "file." + res.ext;

            var link = document.createElement("a");
            link.href = URL.createObjectURL(res.data);
            link.download = filename;
            link.textContent = "PREUZMI FAJL";

            $("#test").html(link);
            break;
          default:
            $("#test").html(res.data);
        }
        $("#loader").removeClass("spinner-border");
      })
      .catch(function (error) {
        console.log(error);
        $("#loader").removeClass("spinner-border");
      });
  });
});
