var devicelist = {};

var labels = [
  { name: "Select Action", serialnumber: 0 }, 
  { name: "Assign New Device", serialnumber: 0 }, 
  { name: "Check Device Status", serialnumber: 0 },
  { name: "", serialnumber: 0 },
  { name: "", serialnumber: 0, cellphone: "" },
  { name: "Unlink Device", serialnumber: 0 },
  { name: "Cancel Contract", serialnumber: 0 }
];

$(document).ready(function() {
  var results = "";
  
  var user = sessionStorage.getItem('user');
  if (user == null || user == undefined) {
      window.location = "index.html";
      // return;  
  }

  util.getClientsdata(data => {
    results = results + data;
    if (results[results.length - 1] != "]") {
      return;
    }
    //console.log(results);
    buildTableData(JSON.parse(results));
  });
});



function moreData() {
  util.getInstaller(function(data) {
    $("#installer").html("");
    $("#soldby").html("");
    data = JSON.parse(data);

    for (j = 0; j < data.length; j++) {
      $("#installer").append(
        $("<option></option>")
          .val(data[j].username)
          .html(data[j].name + " " + data[j].surname)
      );

      $("#soldby").append(
        $("<option></option>")
          .val(data[j].username)
          .html(data[j].name + " " + data[j].surname)
      );
    }
  });
}

function renderBootstrap(data) {
  $("#table-client").bootstrapTable({
    data: data,
    formatLoadingMessage: function() {
      return "<b> Clients (" + data.length + ")</b>";
    }
  });
}

function buildTableData(info) {
  $("#table-client > tbody")
    .find("tr")
    .remove();

  //console.log(info);
  for (i = 0; i < info.length; i++) {
    var rows;

    var registrationnumber = info[i].registrationnumber;
    var serialnumber = info[i].serialnumber;
    var devicecellphone = info[i].devicecellphone;
    var installdate = info[i].installdate;
    var deviceinfo = JSON.stringify(info[i].userdevice);
    deviceinfo = JSON.parse(deviceinfo);
    var certinfo = JSON.stringify(info[i].certdata);
    certinfo = jQuery.parseJSON(certinfo);

    for (j = 0; j < deviceinfo.length; j++) {
      var seriallink =
        "<a href=trip.html?serialnumber=" +
        serialnumber +
        "> " +
        serialnumber +
        "</a>";

      var contractLabel = deviceinfo[j].contractcancelled ==1 ? "Reinstate Contract":"Cancel Contract"; 
      var contract;
      if (deviceinfo[j].contractnumber) {
        var cancelled = "";
        if(deviceinfo[j].contractcancelled == 1) cancelled = "(Cancelled) : ";
        contract =
          '<a href="#" href=usercontract.php?contractnumber=' +
          deviceinfo[j].contractnumber +
          "> " +
         cancelled+  deviceinfo[j].contractnumber +
          "</a>";
      } else {
        contract = " - ";
      }
      var version = deviceinfo[j].version;
      var name = deviceinfo[j].name;
      if(deviceinfo[j].contractcancelled == 1) name = "<font color='red'>"+name+"</font>";
      
      var surname = deviceinfo[j].surname;
      var email = deviceinfo[j].lastupdate;
      var cellphone =
        '<a href="#" onclick="updateuserinfo(\'' +
        deviceinfo[j].cellphone +
        "');\">" +
        deviceinfo[j].cellphone +
        "</a>";

      var deactivated = deviceinfo[j].deactivated;
      var activatelabel =
        deactivated == undefined || deactivated == 0
          ? "Deactivate User"
          : "Activate User";

      var certlabel =
        certinfo.length > 0 ? "View Certificate" : "Capture Certificate Data";
      
      //console.log(deviceinfo[j].cellphone);
      

      rows +=
        "<tr><td>" +
        contract +
        "</td><td>" +
        version +
        "</td><td>" +
        name +
        "</td><td>" +
        surname +
        "</td><td>" +
        email +
        "</td><td>" +
        cellphone +
        "</td><td><a href='report.html?regnumber="+registrationnumber+"'>" +
        registrationnumber +
        "</a> &nbsp;&nbsp;&nbsp;</td><td> "+installdate+" </td><td>" +
        seriallink +
        "</td><td>" +
        devicecellphone +
        "</td><td>" +
        addDropdown(
          serialnumber,
          certlabel,
          activatelabel,
          deviceinfo[j].cellphone,
          contractLabel
        );
      +"</td></tr>";
    }
  }

  $("#table-client")
    .append("<tbody>")
    .append(rows);
  $("#table-client").DataTable();
}

function addDropdown(serialNumber, certlabel, activatelabel, cellphone,contractlabel) {
  var options_str = "";
  labels[3].name = certlabel;
  labels[4].name = activatelabel;
  labels[4].cellphone = cellphone;
  labels[6].name = contractlabel;
  labels[6].cellphone = cellphone;

  labels.sort(function(a, b){
    return a.name > b.name;
  });

  labels.forEach(function(label) {
    label.serialnumber = serialNumber;

    options_str +=
      "<option value='" +
      JSON.stringify(label) +
      "' >" +
      label.name +
      "</option>";
  });

  return (
    '<select id="tableDropDown" onchange="changeDropdown(this.value)" class="form-control">' +
    options_str +
    "</select>"
  );
}

function showHide() {
  $(".sidebar").toggleClass("toggled");
}

function removeAlerts() {
  var elements = document.getElementsByClassName("alert");
  while (elements.length > 0) elements[0].remove();
}

function getClientModalData() {
  $("#imei").val(devicelist[0].imei);
  $("#devicecellphone").val(devicelist[0].devicecellphone);
  $("#serialnnumber").val(devicelist[0].serialnumber);
}

function unlink(serial) {
  util.unlinkdevice(serial,"",function(data){
    alert(data);
  });  
}

function addRemoveClass(cssClass, flag, objkey) {
  var id = "input#" + objkey;

  if (flag) {
    $(id).addClass(cssClass);
  } else {
    $(id).removeClass(cssClass);
  }

  if (objkey == undefined) {
    $("input").removeClass(cssClass);
  }
}

function getMandatoryData(obj,callback) {
  
  obj.serialnumber = devicelist[0].serialnumber;
  obj.cellphone = $("input#cellphone").val();
  obj.name = $("input#name").val();
  obj.surname = $("input#surname").val();
  obj.registrationnumber = $("input#registrationnumber").val();

  obj.idnumber = $("input#idnumber").val();
  obj.taxiassociation = $("input#taxiassociation").val();
  obj.makeofvehicle = $("input#makeofvehicle").val();
  obj.modelofvehicle = $("input#modelofvehicle").val();
  obj.vinnumber = $("input#vinnumber").val();
  obj.color = $("input#color").val();
  obj.installedby = $("input#installer").val();
  obj.soldby = $("#soldby").val();
  //alert($("#soldby").val());

  callback(obj);
}

function getOptionalData(obj,callback) {
  obj.insurancename = $("input#insurancename").val();
  obj.policynumber = $("input#policynumber").val();
  obj.address1 = $("input#address1").val();
  obj.addresscode = $("input#addresscode").val();

  obj.phonemake = $("input#phonemake").val();
  obj.phonemodel = $("input#phonemodel").val();
  callback(obj);
}

function addAlertDiv(div, type, msg) {
  div.innerHTML +=
    '<div class="alert alert-' + type + ' role="alert">' + msg + "</div>";
}

function changeDropdown(value) {
  var selectedInfo = JSON.parse(value);
  console.log(selectedInfo);
  switch (selectedInfo.name) {
    case "Unlink Device":
      unlink(selectedInfo.serialnumber);
      break;
    case "Capture Certificate Data":
      certificatedata(selectedInfo.serialnumber);
      break;
    case "View Certificate":
      getcertificate(selectedInfo.serialnumber);
      break;
    case "Deactivate / Reactivate":
      // code block
      break;
    case "Assign New Device":
      showSerialModal(selectedInfo.serialnumber);
      break;
    case "Check Device Status":
      // code block
    case "Deactivate User":
      deactivate(selectedInfo.cellphone);
      break;
    case "Activate User":
      activate(selectedInfo.cellphone);
      break;
    case "Cancel Contract":
      cancellContract(selectedInfo.cellphone);
      break;
    case "Reinstate Contract":
      reinstateContract(selectedInfo.cellphone);
      break;
  }
}

function showSerialModal(serialnumber) {
  $("#serialModal").modal("show");
  $("#oldserialnumber").val(serialnumber);
}



function certificatedata(serial) {
  window.location = "certificate.html?serialnumber=" + serial;
}

function getcertificate(serial) {
  //window.location = "http://165.73.80.85:3085/install/installationcertificateinfo/"+serial;
  var url = "http://165.73.80.85:3085/install/pdf/" + serial;
  var win = window.open(url, "_blank");
  win.focus();
}

function activate(cellphone) {
  //alert(cellphone);
  util.activate(cellphone, function(data) {
    alert(data);
  });
}

function deactivate(cellphone) {
  //alert(cellphone);
  util.deactivate(cellphone, function(data) {
    alert(data);
  });
}

function cancellContract(cellphone) {
  //alert(cellphone);
  util.cancellContract(cellphone, function(data) {
    alert("Contract Cancelled");
  });
}

function reinstateContract(cellphone) {
  //alert(cellphone);
  util.reinstateContract(cellphone, function(data) {
    alert("Contract Reinstated");
  });
}

$("#btn_save").click(function() {
  var obj = {};
  var error = false;
  var div = document.getElementById("clientBody");
  
  removeAlerts();
  getMandatoryData(obj,(obj)=>{
    Object.entries(obj).forEach(([key, val]) => {
      if (val == "") {
        error = true;
        addRemoveClass("red-border", true, key);
      } else {
        addRemoveClass("red-border", false, key);
      }
    });
  
    if (error) {
      getClientModalData();
      return;
    }
  
    getOptionalData(obj,(obj)=>{
      console.log(obj);
  
      util.saveClientData(obj, data => {
        addAlertDiv(div, "info", data);
        //getClientModalData();
        location.reload();
      });
    });
    
  });  
});

$("#btn_check").click(function() {
  removeAlerts();

  var div = document.getElementById("searchBody");
  var btnText = document.getElementsByClassName("btn").btn_check.innerText;
  var serialnumber = $("#checkserialnumber")
    .val()
    .trim();

  if (btnText == "Check") {
    if (serialnumber == undefined || serialnumber == "") {
      addAlertDiv(div, "warning", "Please enter valid serial number.");
      return;
    }

    util.checkSerialNumber(serialnumber, data => {
      data = JSON.parse(data);
      console.log(data);
      if (data.length > 0) {
        devicelist = data;
        document.getElementsByClassName("btn").btn_check.innerText =
          "Add New Client";
        addAlertDiv(
          div,
          "success",
          "Serial number <b>" + serialnumber + "</b> available for installation."
        );
      } else {
        addAlertDiv(
          div,
          "danger",
          "Serial number <b>" +
            serialnumber +
            "</b> does not exist or already been used."
        );
      }
    });
  } else {
    moreData();

    $("#searchModal").modal("hide");
    $("#clientsModal").modal("show");
    $("input").val("");
    addRemoveClass("red-border");

    getClientModalData();
  }
});

$("#searchModal").on("show.bs.modal", function() {
  devicelist = {};
  $(".modal").focus();
  document.getElementsByClassName("btn").btn_check.innerText = "Check";
  removeAlerts();
});

$("#clientForm").submit(event => {
  event.preventDefault();
});

$("#btn_replace").click(function() {
  removeAlerts();

  var error = false;
  var div = document.getElementById("serialBody");
  var oldserialnumber = $("#oldserialnumber").val();
  var newSerialnumber = $("#newserialnumber")
    .val()
    .trim();

  if (newSerialnumber == undefined || newSerialnumber == "") {
    error = true;
  } else if (!$.isNumeric(newSerialnumber)) {
    error = true;
  }

  if (error) {
    addAlertDiv(div, "warning", "Please enter valid serial number.");
    $("#oldserialnumber").val(oldserialnumber);
    return;
  }

  util.replacedevice(oldserialnumber, newSerialnumber, function(data) {
    alert(data);
  });
});
