/**
 * @copyright 2021 Double Bastion LLC <www.doublebastion.com>
 *
 * @author Double Bastion LLC
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

$(document).ready(function() {

    // Delete from the database all the received messages older than the specified period
    $("#delOldrecSMS").on("click", function() {

      var oldrecInterval = $("#oldrecSmsInterval").val();
      var procoldrecint = oldrecInterval.replace(/[^0-9]/g, "");
      var finaloldrecint = parseInt(procoldrecint);

      if (finaloldrecint == "" || !$.isNumeric(finaloldrecint)) {
          showAlert("Please enter the number of days in the box from above !");
      } else {

         var getRecUrl = OC.generateUrl("/apps/sms_relentless/user/getreceivedtablefordel");
         $('#smstables').addClass('icon-loading');

         $.ajax({
             url: getRecUrl,
             method: "GET",
             dataType:'text',
             success: function(recinfoFromDB) {

                var parsedinfo = $.parseJSON(recinfoFromDB);

                if (parsedinfo == "not permitted") {

                    showAlert("Only admins can remove old messages using this option!");
                    $('#smstables').removeClass('icon-loading');
                    return;

                } else {

                    var recmessagedbIDs = [];
                    var oldrecRows = [];
                    oldrecRows.push("id,user_id,message_id,date,from,to,message,author_displayname,internal_sender\r\n");

                    var targetdate = new Date(new Date().setDate(new Date().getDate() - finaloldrecint));

                    for (var j = 0; j < parsedinfo.length; j++) {
                         var firstdate = parsedinfo[j].date;
                         var secdate = firstdate.split(" ");
                         var thirddate = secdate[0].split("-");
                         var fourthdate = secdate[1].split(":");
                         var pastdate = new Date(thirddate[0],(thirddate[1]-1),thirddate[2],fourthdate[0],fourthdate[1],fourthdate[2]);

                         if (pastdate < targetdate) {
                             recmessagedbIDs.push(parsedinfo[j].id);

                             // Check if the message contains characters that must be escaped in the final CSV file
                             if ((parsedinfo[j].message.indexOf(',') > -1 || /\r|\n|\r\n/.exec(parsedinfo[j].message)) && parsedinfo[j].message.indexOf('"') === -1) {
                                 var messageproc = '"'+ parsedinfo[j].message + '"';
                             } else if (parsedinfo[j].message.indexOf('"') > -1) {
                                 var messageproc = '"'+ parsedinfo[j].message.replace(/"/g,'""') + '"';
                             }

                             oldrecRows.push(parsedinfo[j].id + ',' + parsedinfo[j].user_id + ',' + parsedinfo[j].message_id + ',' + parsedinfo[j].date + ',' + parsedinfo[j].from + ',' + parsedinfo[j].to + ',' + messageproc + ',' + parsedinfo[j].author_displayname + ',' + parsedinfo[j].internal_sender + '\r\n');
                         }
                    }


                    if (oldrecRows.length == 1) {

                        showAlert("No messages will be deleted since there are no messages older than " + finaloldrecint + " days.");

                    // Save in a '.csv' file all the received messages that will be deleted from the database, then delete them
                    } else {

                        confirmAlert("Are you sure you want to delete all the received messages older than " + finaloldrecint + " days ?");

                        $("#confirmCancel").click(function() { $("#alertMsgOverlay").remove(); $("#alertConfMessage").remove(); });

                        $("#confirmOk").click(function() {

                            $("#alertMsgOverlay").remove();
                            $("#alertConfMessage").remove();

                            var deloldrecRowsUrl = OC.generateUrl("/apps/sms_relentless/user/saveoldrecrows");

                            $.ajax({
                                url: deloldrecRowsUrl,
                                method: "POST",
                                dataType:'text',
                                data: { oldrecRows: oldrecRows },
                                success: function(savecheck) {

                                            // Delete received messages from the database
                                            var delrecDbSmsUrl = OC.generateUrl("/apps/sms_relentless/user/removerecrows");

                                            if (savecheck == 1) {

                                                $.ajax({
                                                       url: delrecDbSmsUrl,
                                                       method: "POST",
                                                       dataType:'text',
                                                       data: { recmessagedbIDs: recmessagedbIDs },
                                                       success: function() {
                                                            showAlert((oldrecRows.length - 1)+" rows have been successfully saved in the 'SMS_relentless/removed_received_messages' directory and then deleted from the database !");
                                                            $('#smstables').removeClass('icon-loading');
                                                       },
                                                       error: function() {
                                                            showAlert("There was an error while deleting the messages older than the specified period!");
                                                            $('#smstables').removeClass('icon-loading');
                                                       }
                                                });

                                            } else { showAlert("There was an error while saving the messages older than the specified period!"); }

                                            $('#smstables').removeClass('icon-loading');
                                },
                                error: function() {
                                     showAlert("There was an error while saving and/or deleting the messages older than the specified period!");
                                     $('#smstables').removeClass('icon-loading');
                                }
                            });
                        });
                    }
                }
             },
             error: function() {
                showAlert("An error occurred while getting data from the database!");
                $('#smstables').removeClass('icon-loading');
             }
         });

      }

    });


    // Delete from the database all the sent messages older than the specified period
    $("#delOldsentSMS").on("click", function() {

      var oldsentInterval = $("#oldsentSmsInterval").val();
      var procoldsentint = oldsentInterval.replace(/[^0-9]/g, "");
      var finaloldsentint = parseInt(procoldsentint);

      if (finaloldsentint == "" || !$.isNumeric(finaloldsentint)) {
          showAlert("Please enter the number of days in the box above !");
      } else {

         var getSentUrl = OC.generateUrl("/apps/sms_relentless/user/getsenttablefordel");
         $('#smstables').addClass('icon-loading');

         $.ajax({
             url: getSentUrl,
             method: "GET",
             dataType:'text',
             success: function(sentinfoFromDB) {

                var parsedsentinfo = $.parseJSON(sentinfoFromDB);

                if (parsedsentinfo == "not permitted") {

                    showAlert("Only admins can remove old messages using this option!");
                    $('#smstables').removeClass('icon-loading');
                    return;

                } else {

                    var sentmessagedbIDs = [];
                    var oldsentRows = [];
                    oldsentRows.push("id,user_id,message_id,date,from,to,network,price,status,deliveryreceipt,message,author_displayname\r\n");

                    var senttargetdate = new Date(new Date().setDate(new Date().getDate() - finaloldsentint));

                    for (var j = 0; j < parsedsentinfo.length; j++) {
                         var firstdate = parsedsentinfo[j].date;
                         var secdate = firstdate.split(" ");
                         var thirddate = secdate[0].split("-");
                         var fourthdate = secdate[1].split(":");
                         var sentpastdate = new Date(thirddate[0],(thirddate[1]-1),thirddate[2],fourthdate[0],fourthdate[1],fourthdate[2]);

                         if (sentpastdate < senttargetdate) {
                             sentmessagedbIDs.push(parsedsentinfo[j].id);

                             // Check if the message contains characters that must be escaped in the final CSV file
                             if ((parsedsentinfo[j].message.indexOf(',') > -1 || /\r|\n|\r\n/.exec(parsedsentinfo[j].message)) && parsedsentinfo[j].message.indexOf('"') === -1) {
                                 var messageproc = '"'+ parsedsentinfo[j].message + '"';
                             } else if (parsedsentinfo[j].message.indexOf('"') > -1) {
                                 var messageproc = '"'+ parsedsentinfo[j].message.replace(/"/g,'""') + '"';
                             }

                             if ((parsedsentinfo[j].network.indexOf(',') > -1 || /\r|\n|\r\n/.exec(parsedsentinfo[j].network)) && parsedsentinfo[j].network.indexOf('"') === -1) {
                                 var networkproc = '"'+ parsedsentinfo[j].network + '"';
                             } else if (parsedsentinfo[j].network.indexOf('"') > -1) {
                                 var networkproc = '"'+ parsedsentinfo[j].network.replace(/"/g,'""') + '"';
                             }

                             if ((parsedsentinfo[j].status.indexOf(',') > -1 || /\r|\n|\r\n/.exec(parsedsentinfo[j].status)) && parsedsentinfo[j].status.indexOf('"') === -1) {
                                 var statusproc = '"'+ parsedsentinfo[j].status + '"';
                             } else if (parsedsentinfo[j].status.indexOf('"') > -1) {
                                 var statusproc = '"'+ parsedsentinfo[j].status.replace(/"/g,'""') + '"';
                             }

                             oldsentRows.push(parsedsentinfo[j].id + ',' + parsedsentinfo[j].user_id + ',' + parsedsentinfo[j].message_id + ',' + parsedsentinfo[j].date + ',' + parsedsentinfo[j].from + ',' + parsedsentinfo[j].to + ',' + networkproc + ',' + parsedsentinfo[j].price + ',' + statusproc + ',' + parsedsentinfo[j].deliveryreceipt + ',' + messageproc + ',' + parsedsentinfo[j].author_displayname + '\r\n');
                         }
                    }


                    if (oldsentRows.length == 1) {

                        showAlert("No messages will be deleted since there are no messages older than " + finaloldsentint + " days.");

                    // Save in a '.csv' file all the sent messages that will be deleted from the database, then delete them
                    } else {

                          confirmAlert("Are you sure you want to delete all the sent messages older than " + finaloldsentint + " days ?");

                          $("#confirmCancel").click(function() { $("#alertMsgOverlay").remove(); $("#alertConfMessage").remove(); });

                          $("#confirmOk").click(function() {

                              $("#alertMsgOverlay").remove();
                              $("#alertConfMessage").remove();

                              var deloldsentRowsUrl = OC.generateUrl("/apps/sms_relentless/user/saveoldsentrows");

                              $.ajax({
                                  url: deloldsentRowsUrl,
                                  method: "POST",
                                  dataType:'text',
                                  data: { oldsentRows: oldsentRows },
                                  success: function(savesentcheck) {

                                            // Delete sent messages from the database
                                            var delsentDbSmsUrl = OC.generateUrl("/apps/sms_relentless/user/removesentrows");

                                            if (savesentcheck == 1) {

                                                $.ajax({
                                                       url: delsentDbSmsUrl,
                                                       method: "POST",
                                                       dataType:'text',
                                                       data: { sentmessagedbIDs: sentmessagedbIDs },
                                                       success: function() {
                                                            showAlert((oldsentRows.length - 1) + " rows have been successfully saved in the 'SMS_relentless/removed_sent_messages' directory and then deleted from the database !");
                                                            $('#smstables').removeClass('icon-loading');
                                                       },
                                                       error: function() {
                                                            showAlert("There was an error while deleting the messages older than the specified period!");
                                                            $('#smstables').removeClass('icon-loading');
                                                       }
                                                });

                                            } else { showAlert("There was an error while saving the messages older than the specified period!"); }

                                            $('#smstables').removeClass('icon-loading');
                                  },
                                  error: function() {
                                     showAlert("There was an error while saving and/or deleting the messages older than the specified period!");
                                     $('#smstables').removeClass('icon-loading');
                                  }
                              });
                          });
                    }
                }  

             },
             error: function() {
                showAlert("An error occurred while getting data from the database!");
                $('#smstables').removeClass('icon-loading');
             }
         });
      }

    });

    function showAlert(alertText) {

       let alertwnd = "<div id='alertMessage'>";
       alertwnd += "<a id='closeAlertWnd' title='Close this window'></a>";
       alertwnd += "<div id='alertTextWrap'>"+ alertText +"</div>";
       alertwnd += "<input type='submit' id='alertOk' value='OK'>";
       alertwnd += "</div>";

       $("#content").append("<div id='alertMsgOverlay'></div>");
       $("#content").append(alertwnd);

       let topDist = parseInt((window.innerHeight / 2).toFixed(2) - 152) +"px";
       let leftDist = parseInt((window.innerWidth / 2).toFixed(2) - 150) +"px";
       $("#alertMessage").css({ "top" : topDist, "left" : leftDist });

       $("#closeAlertWnd").click(function() { $("#alertMsgOverlay").remove(); $("#alertMessage").remove(); });
       $("#alertMsgOverlay").click(function() { $("#alertMsgOverlay").remove(); $("#alertMessage").remove(); });
       $("#alertOk").click(function() { $("#alertMsgOverlay").remove(); $("#alertMessage").remove(); });
    }

    function confirmAlert(alertText) {

       $("#alertMsgOverlay").remove();
       $("#alertConfMessage").remove();

       let alertwndcf = "<div id='alertConfMessage'>";
       alertwndcf += "<a id='closeAlertWndcf' title='Close this window'></a>";
       alertwndcf += "<div id='alertTextWrap'>"+ alertText +"</div>";
       alertwndcf += "<div id='cancelOkWrap'><input type='submit' id='confirmCancel' value='Cancel'>";
       alertwndcf += "<input type='submit' id='confirmOk' value='OK'></div>";
       alertwndcf += "</div>";

       $("#content").append("<div id='alertMsgOverlay'></div>");
       $("#content").append(alertwndcf);

       let topDist = parseInt((window.innerHeight / 2).toFixed(2) - 152) +"px";
       let leftDist = parseInt((window.innerWidth / 2).toFixed(2) - 150) +"px";
       $("#alertConfMessage").css({ "top" : topDist, "left" : leftDist });

       $("#closeAlertWndcf").click(function() { $("#alertMsgOverlay").remove(); $("#alertConfMessage").remove(); });
       $("#alertMsgOverlay").click(function() { $("#alertMsgOverlay").remove(); $("#alertConfMessage").remove(); });
    }
});
