
// whh 2019.11.28 read data/SMSmessages.json and display on home page
// whh 2019.12.17 add 'read' field to highlight unread messages
// whh 2020.02.19 switched to calling PHP to read data files uploading to JS with AJAX

// from <view-messages>  Button on webpage
      $("#messageview").click(function(){
          showmessages();
        });
/*
// These are the variables in the message json file
 [
     {
        "clientId": "1Select_Client",
        "number": "Sender",
        "message": "SMS message",
        "dateTime": "Time sent",
        "recipient": "Recipient",
        "localdateTime": "Thursday, 05-Dec-19 16:35:50 EST",
        "read": ""  or "yes"
     }
 ]
*/

/*   Display a Client List in add/new client window */
function showmessages() {

console.log("function showmessages - viewSMSmessages.js -"); // message for browser console for debugging

        // get phone number being used
    var source = document.getElementById("phoneNumber").textContent;
        // console.log (source);
    var phoneNumber = document.getElementById("phoneNumberSource").innerHTML;

        // get selected name
        var valSelected = document.getElementById("selected").value; // get selected name
//console.log("selected Client: " + valSelected);
        // get entered name
        var valEntered = document.getElementById("recipient").value; // get selected name
//console.log("Entered Client: " + valEntered);


// figure out if select phone or manually entered number is to new used
  if (valEntered  === "") {
    var val = valSelected;
//console.log("it is valSelected: " + val);
      } else {
        var val = valEntered;
//console.log("else valEntered: " + val);
    };

// Parse ClientID from Selected3 for phone number
  var n = val.indexOf(":"); //how many characters to the colon
//console.log("n: " + n );
  var valn = val.substring(n+1); // +2 for colom and space
  var valn = valn.replace(/ /g,'');


//console.log("selected Client after n: " + valn);


/* 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);
        length = data.length;

          // Sort data by date
            data.sort(function(a, b) {
                a = new Date(a.dateTime);
                b = new Date(b.dateTime);
                return a<b ? -1 : a>b ? 1 : 0;
            });

        //console.table(data);

//console.log("selected Client after n: " + valn);

// find just the elements selected for the Phone number of val
        var obja = $.grep(data, function(obj, i){return obj.number === valn;});

        //console.table(obja);

//******************************************************************
// load the Sent Messages file
//******************************************************************
                    $.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(data) {
                            // console.log("unsorted dates:")
                            //console.table(data);
                            //console.log("Data Length from file: " + data.length);

                            length2 = data.length;
                            // Sort data by date
                            data.sort(function(a, b) {
                                a = new Date(a.dateTime);
                                b = new Date(b.dateTime);
                                return a<b ? -1 : a>b ? 1 : 0;
                            });
                            //console.table(data);

// find just the elements selected for the Phone number of source and selected incoming client
    // console.log("source: " + source + " - valn: " + valn);
                            var objins = $.grep(data, function(obj, i){return obj.recipient === valn;});
                            var objin = $.grep(objins, function(obj, i){return obj.number === source;});

                            //console.table(objins);
                            //console.table(objin);

//******************************************************************
// End load Sent messages
//******************************************************************


// clear window content and add clientInfo
// document.getElementById("messageWindowtitle").innerHTML = "<p style='color:#216bd1;}'>" + "<strong> SMS from: " + val + "</strong></p>";

// list all of a SMS message for a phone mumber recieved

if (length <= length2) {
  var uselength = length2;
//console.log("uselength: " + uselength);
    } else {
      var uselength = length;
//console.log("uselength: " + uselength);
  };

var k = 0;
var bcolor = "#bdbdbd;";
  for (k=0; k < uselength; k++){

    if (k < obja.length ){

        // set background of unread messages to light green
        if(obja[k].read === "no"){bcolor = "#abfc79;"; } else {bolor = "#bdbdbd;";}

        var message =  "<strong>Received Message:</strong> " + obja[k].message
          + "<br><strong>Date and Time:</strong> " + obja[k].dateTime + "<br>"
          + obja[k].clientId;

          var message2 = "<div class='row p-2 '><div class='col-8' style = 'text-align: left; border-radius: 15px; background-color:" + bcolor + "color:black; position: relative;  z-index:999;'>" + message + "</div></div>";
          document.getElementById('newWindows').innerHTML += "SMS Received: " + message2;
          //console.log("Display 1 ");
      }

          // list all of a SMS message for phone mumber
      if (k < objin.length ){

          var message =  "<strong>Sent Message:</strong> " + objin[k].messagein
                    + "<br><strong>Date and Time:</strong> " + objin[k].dateTime + "<br>"
                    + objin[k].clientId;

          var message2 = "<div class='row p-2 '><div class='col-8 offset-4' style = 'text-align: left; border-radius: 15px; background-color:#bed3e6; color:black; position: relative;  z-index:999;'>" + message + "</div></div>";
          document.getElementById('newWindows').innerHTML += "<span style='color:#9fc7ed;'>SMS Sent:<span> " + message2;
          //console.log("Display 2 ");
      }
    } // k for loop

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



} //SMSmesages success

}); // end of SMSmesages ajax
document.getElementById('newWindows').innerHTML += "<div id='view3'></div>";

$([document.documentElement, document.body]).animate({
    scrollTop: $("#view3").offset().top
}, 1000 );

    // endStop:
/*
    // go to view SMS messages
              $([document.documentElement, document.body]).animate({
                 scrollTop: $("#view3").offset().top
               }, 1000);
*/


}; // end of entire function
