
// PAGE 4
// whh 2020.03.06 this is PAGE 4 and displays all messages in SMSmessagesSent and SMSmessages
// whh 2020.03.19 all console logs commented out
//
//


function phonesNumbersListAll(source) {

console.log("Runnning  - phoneNumbersListAll.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-6' style=' align-text:left !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='phonesNumbersList(" + source + ")' ><span class='glyphicon glyphicon-backward'></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-6' 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 newMess = "<div class='col-12 p4 '>Received Messages<br></div>";
  var pushDown = "<div class='col-12 p4 horzline'><br></div>";

  document.getElementById("newPhoneList").innerHTML = backNumber2 + newContact;
  //document.getElementById("newPhoneList").innerHTML += newMess;
  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; // all the cobtact information



// 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
*/



// ####################################################################

  /* read in the incoming client messages from SMSmessagesSent.json */
  /* read in the incoming client messages from SMSmessagesSent.json */
  /* read in the incoming client messages from SMSmessagesSent.json */
          $.ajax({
              url: "SMSMessagesSentAjax.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(data3) {
                //console.table(data);
                //console.log("Data Length from file: " + data.length);
          //console.table(data);
          lengthRCSent = data3.length; // all the recieved messages

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

  var objaSent = data3;

  // Use only messages for this source that have been sent
  // Use only messages for this source that have been sent
  // Use only messages for this source that have been sent
  var objaSourceSent = $.grep(objaSent, function(obj, i){return obj.number == source ;});
    //console.table(objaSourceSent);

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

  var sentMess = "<div class='col-12 p4 '>Sent Messages<br></div>";
  document.getElementById("newPhoneList").innerHTML += sentMess;

  var k = 0;
  var initials = "";

    lengthSourceSent = objaSourceSent.length; // total sent messages
      //console.log("lengthNew: "  + lengthNew );

var objnewaNumber = source ;
  // go thought all the contacts

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

      if (objnewaNumberTest != objaSourceSent[k].recipient) {

  try {

    //console.log("Try One" );

      var objnewaNumberTest = objaSourceSent[k].recipient;
      var objnewaNumber = objaSourceSent[k].recipient;

      var objbSent = $.grep(objId, function(obj, i){return obj.phone == objnewaNumber ;});
      var objnewaNumber = objaSourceSent[k].recipient;
      var readaSent = objbSent.length;
      //console.table(objbSent);

        try {

      //console.log("Try Two" );
            var contactNumberSent = objbSent[0].phone;
            var contactInitialsSent = objbSent[0].initials;
            var firstNameSent = objbSent[0].firstname;
            var lastNameSent = objbSent[0].name;

            }
              catch ( e ) {
                var contactNumberSent = "newContact";
                var contactInitialsSent = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; // fill with spaces to keep bubble same size as 2 letter initials
                var firstNameSent = objnewaNumber;
                var lastNameSent = " ";
                    //console.log("an error in try" );

        }

    }
    catch ( e ) {

    }

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

      if (k < lengthRCSent  ) {

//console.log("objnewaNumber: "  + objnewaNumber );
//console.log("source: "  + source);
//console.log("clientId: "  + objaSent[k].clientId);

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

   var message =  "<strong>Received Message:</strong> " + objaSent[k].message
     + "<br><strong>Date and Time:</strong> " + objaSent[k].dateTime + "<br>"
     + objaSent[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> " + contactInitialsSent + " </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='" + firstNameSent + " " + lastNameSent + "' onClick='newClientMessages(" + objnewaNumber + "," + source +")'></input></div>";

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

                } // loop3
              } // loop2
            } // loop1

          }  // end of success  SMSmesageSENT json ajax LOOP
        }); // end of SMSmesageSENT json 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(objaSent) {

  var original = objaSent;
	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(objaSent));
	// 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;
};
