
// PAGE 2
// whh 2020.01.08 this is PAGE 2 and displays number with messages and count
// whh 2020.02.19 switched to calling PHP to read data files uploading to JS with AJAX
//


function phonesNumbersList(source) {

console.log("Runnning  - phoneNumberList.js -"); // message for browser console for debugging

  document.getElementById("sms").style.display = "none";
  document.getElementById("phone").style.display = "none";
  document.getElementById("numpad").style.display = "none";
  document.getElementById("selectNUM").style.display = "none";
  document.getElementById("newPhoneList").style.display = "block";
  document.getElementById("contactSubmit").style.display = "none";
  document.getElementById("firstName").style.display = "block";
  document.getElementById("lastName").style.display = "block";
  document.getElementById("phoneNumberSource").style.display = "block";
  document.getElementById("phoneNumberSource").style.fontSize = "0.75em";
  document.getElementById("phoneNumberSource").style.color = "white";
  document.getElementById("phoneNumberSource").style.textAlign = "center"
  document.getElementById("messageText").style.marginTop = "0px";

  document.getElementById("mail").style.display = "none";
  document.getElementById('notes').style.display = "none";
  document.getElementById('type').style.display = "none";
  document.getElementById('typeDelete').style.display = "none";

      console.log("SOURCE: " + source);

  document.getElementById("phoneNumberSource").innerHTML = source;
  document.getElementById('newPhoneList').innerHTML = "&nbsp;";


  // back button to numbers under the current source
  //var backNumber2 = " <div class='row phonenumbers horzline p-2'> <div class='col-4 p-2'> <input class='btn btn-outline-secondary actionbtn'type='button' value='Back' onClick='newMessages()' > </input></div> ";

  var backNumber2 = " <div class='row phonenumbers' style='position:fixed; z-index:999999; background-color:rgba(0, 0, 0, 0)!Important; margin-top:-20px; width:100%;'> <div class='col-4' style=' align-text:right !important;  background-color:rgba(0, 0, 0, 0)!Important;'> <button class='btn btn-link backarrow' style='background-color:rgba(0, 0, 0, 0) !Important;' type='button' onClick='newMessages()' ><span class='glyphicon glyphicon-backward'></span></button></div> ";
  var sentMessages = " <div class='col-4' style=' align-text:center   background-color:rgba(0, 0, 0, 0)!Important;'> <button class='btn btn-link sendplane' style='background-color:rgba(0, 0, 0, 0); margin-top:10px!important; !Important;' type='button' onClick='phonesNumbersListAll(" + source + ")' ><span class='glyphicon glyphicon-send'></span></button></div> ";

  // var selContact = "<div class='col-4'><input class='btn btn btn-outline-secondary actionbtn' type='button' value='Contacts' onClick='sendUsingContacts(" + source + ")'></input></div>";

  // option to sent to a new phone number at top
  // var newContact = "<div class='col-4 p-2'><input class='btn btn btn-outline-secondary actionbtn' type='button' value='Enter Number' onClick='newContactNumberMessages(" + source + ")'></input></div> </div>";
  var newContact = "<div class='col-4' style='align-text:right !important;' ><button class='btn btn-link plussign' type='button' onClick='newContactNumberMessages(" + source + ")' ><span class='glyphicon glyphicon-plus'></span></button></div></div>";

  var pushDown = "<div class='col-12 p4 horzline'><br><br><br></div>";

  document.getElementById("newPhoneList").innerHTML = backNumber2 + sentMessages + newContact ;
    document.getElementById("newPhoneList").innerHTML += pushDown;

  // make this input required for this useage
  document.getElementById("recipient").required  = true;

  // clear sent message information field
  document.getElementById("form-messages").innerHTML = " " ;

  		//$('#type').val('');

var source = source ;


// Load ClientId files data
    $.ajax({
        url: "ContactsAjax.php",
        async: false,   // asynchronous request? (synchronous requests are discouraged...)
        cache: false,   // with this, you can force the browser to not make cache of the retrieved data
        dataType: "json",  // jQuery will infer this, but you can set explicitly
        success: function(data2) {
    //console.table(data2);
    //console.log(data2.length);
          var lengthId = data2.length;
          var objId = data2;



/* read in the incoming client messages from SMSmessages.json */
/* read in the incoming client messages from SMSmessages.json */
/* read in the incoming client messages from SMSmessages.json */
        $.ajax({
            url: "SMSMessagesAjax.php",
            async: false,   // asynchronous request? (synchronous requests are discouraged...)
            cache: false,   // with this, you can force the browser to not make cache of the retrieved data
            dataType: "json",  // jQuery will infer this, but you can set explicitly
            success: function(data) {
              //console.table(data);
              //console.log("Data Length from file: " + data.length);
        //console.table(data);
        lengthRC = data.length; // all the recieved messages

          // Sort data by date
            data.sort(function(a, b) {
                  return new Date(b.localdateTime) - new Date(a.localdateTime);
            });
            //console.table(data);

var obja = data;

// Use only messages for this source calling
// Use only messages for this source calling
// Use only messages for this source calling

var objaSource = $.grep(obja, function(obj, i){return obj.recipient == source ;});

var newSMScountUnusorted = compressArray(objaSource);
//console.table(newSMScountUnusorted);

// Sort data by date
  newSMScountUnusorted.sort(function(a, b) {
      return new Date(b.localdateTime) - new Date(a.localdateTime);
  });

var newSMScount = newSMScountUnusorted;

//console.table(newSMScount);

var k = 0;
var initials = "";

  lengthNew = newSMScount.length; // total New messages


// go thought all the contacts

for (k=0; k < lengthNew ; k++){

try {
    var objnewaNumber = newSMScount[k].value;
    var reada = newSMScount[k].count;
    var objb = $.grep(objId, function(obj, i){return obj.phone == objnewaNumber ;});
      try {
          var contactNumber = objb[0].phone;
          var contactInitials = objb[0].initials;
          var firstName = objb[0].firstname;
          var lastName = objb[0].name;

          }
            catch ( e ) {
              var contactNumber = "newContact";
              var contactInitials = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; // fill with spaces to keep bubble same size as 2 letter initials
              var firstName = objnewaNumber;
              var lastName = " ";

      }

  }
  catch ( e ) {

  }

//console.log( contactNumber + " - " + contactInitials);

    if (k < lengthRC ) {


//if (objId[n].clientId == obja[k].clientId ) {initials = objId[n].initials; };

 var message =  "<strong>Received Message:</strong> " + obja[k].message
   + "<br><strong>Date and Time:</strong> " + obja[k].dateTime + "<br>"
   + obja[k].clientId;
   //console.log("reada: " + reada);
    // var message1 = "<div class='row phonenumbers horzline justify-content-center'><div class='col-2 p-2 float-right text-right'><input  id='ph4' class='btn initials' type='button' value='"+ contactInitials + "'></input></div>";
   var message1 = "<div class='row phonenumbers horzline justify-content-center'>"
   var message2 = "<div class='col-2 p-2'><button class='btn initials' disabled> " + contactInitials + " </button></div>";
   //var message3 = "<div class='col-6 p-2'><input  class='myphonebtns' type='button' value='" + objnewaNumber + "' onClick='newClientMessages(" + objnewaNumber + "," + source +")'></input></div>";
   var message3 = "<div class='col-6 p-2'><input  class='myphonebtns' type='button' value='" + firstName + " " + lastName + "' onClick='newClientMessages(" + objnewaNumber + "," + source +")'></input></div>";

   var message4 = "<div class='col-2 p-2'><button  class='smsbtn' disabled> " + reada + " </button></div>";
   var message5 = "</div>";
   document.getElementById('newPhoneList').innerHTML += message1 + message2 + message3 + message4 + message5;
   //console.log("Display 1 ");

              } // loop2
            } // loop1

        }  // end of success  SMSmesageson ajax LOOP
      }); // end of SMSmesageson ajax

    } // end of success MAIN LOOP
  }); // load client data

} // End function phoneNumberList


//****************************************************************************

/**
Problem:
You have a javascript array that likely has some duplicate values and you would like a count of those values.
Solution:
Try this schnippet out.
*/
// https://gist.github.com/ralphcrisostomo/3141412

function compressArray(obja) {

  var original = obja;
	var compressed = [];
	// make a copy of the input array but run through JSON to make it a unique copy
  var copy = JSON.parse(JSON.stringify(obja));
	// var copy = obja.slice(0);
	// first loop goes over every element
	for (var i = 0; i < original.length; i++) {
		var myCount = 0;
		// loop over every element in the copy and see if it's the same
		            for (var w = 0; w < copy.length; w++) {
                  //console.log ( "i: " + i + " - " + original[i].number + " = " + "w: " + w + " - " + copy[w].number);
			                if (original[i].number === copy[w].number) {
				                    // increase amount of times duplicate is found
				                  myCount = myCount + 1;
                            //console.log("mycount: " + myCount);
				                    // sets item to undefined
                            //console.table(copy);
                            //console.table(original);
                            copy[w].number = "undefined";
                           //console.table(copy);
                           //console.table(original);
			                 }
		            }
		if (myCount > 0) {
			var a = new Object();
      a.localdateTime = original[i].localdateTime;
			a.value = original[i].number;
      // console.log("a.value: " + a.value);
			a.count = myCount;
			compressed.push(a);
      // console.table(compressed)
		}
	}
//console.table(compressed);
	return compressed;
};
