/**
 * @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() {

  var userid = "<?php p($userId); ?>";
  var baseUrlget = OC.generateUrl('/apps/sms_relentless/user/getadminsettings');

  $.ajax({
     method: 'GET',
     url: baseUrlget + '/' + userid,
     contentType: 'application/json',
     success: function(settingsadm) {

          if (settingsadm.show_all_messages == 1) {
              $("#showallmessages").attr("checked", true);
          } else {
              $("#showallmessages").attr("checked", false);
          }

          var crntadmDispName = settingsadm.admdisplayname;
          var allRestrictions = settingsadm.restrictions;
          var allGroups = settingsadm.allgroups;
          var allUsers = settingsadm.allusers;

          if (allRestrictions.length > 0) { 
              var restrNmb = allRestrictions.length;
          } else { 
              var restrNmb = 0; 
          }


	  // List the access restrictions for groups and users
          if (restrNmb == 0) {

              $("#phoneNmbrRestr").append("<tr><td><input type='text' class='restrAuthor' value='"+ crntadmDispName +"' disabled></td><td><select id='rstphn-"+ restrNmb +"' class='restrPhoneNmbr'></select></td><td><div id='rstgrp-"+ restrNmb +"' class='restrGroups'></div></td><td><div id='showGrps-"+ restrNmb +"' class='showAllGroups'><img src='/apps/sms_relentless/img/group.svg' style='cursor:pointer' title='Show all groups'></div></td><td><div id='rstusr-"+ restrNmb +"' class='restrUsers'></div></td><td><div id='showUsr-"+ restrNmb +"' class='showAllUsers'><img src='/apps/sms_relentless/img/user.svg' style='cursor:pointer' title='Show all users'></div></td><td><img id='rmRow-"+ restrNmb +"' class='removeRow' src='/apps/sms_relentless/img/close.svg' title='Remove this row from the database' style='cursor:pointer;margin:6px 7px 0px 6px;'></td><td><input type='submit' id='rstsave-"+ restrNmb +"' class='saveRestrictions' value='Save' title='Save Row' /></td></tr>");
	      $("#phoneNmbrRestr").append("<div><img id='addRestrRow' src='/apps/sms_relentless/img/add.svg' title='Add Row'></div>");

          } else {

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

                   if (allRestrictions[k].groups) {
                       var groupsfdbpre = allRestrictions[k].groups.split("|");
                       var groupsfdb = "";
                       for (var g = 0; g < groupsfdbpre.length; g++) {
                            groupsfdb += "<div class='selectedGrps'>"+ groupsfdbpre[g] +"<img id='rmvGrp-"+ groupsfdbpre[g] +"' class='removeGroup' src='/apps/sms_relentless/img/close.svg' title='Remove this group'></div>";
                       }
                   } else { var groupsfdb = ""; }

                   if (allRestrictions[k].users) {
                       var usersfdbpre = allRestrictions[k].users.split("|");
                       var usersfdb = "";
                       for (var u = 0; u < usersfdbpre.length; u++) {
                            usersfdb += "<div class='selectedUsrs'>"+ usersfdbpre[u] +"<img id='rmvUsr-"+ usersfdbpre[u] +"' class='removeUser' src='/apps/sms_relentless/img/close.svg' title='Remove this user'></div>";
                       }
                   } else { var usersfdb = ""; }

		   $("#phoneNmbrRestr").append("<tr><td><input type='text' class='restrAuthor' value='"+ allRestrictions[k].saved_by_dsplname +"' disabled></td><td><select id='rstphn-"+ k +"' class='restrPhoneNmbr' style='pointer-events:none'><option selected>"+ allRestrictions[k].phone_number +"</option></select></td><td><div id='rstgrp-"+ k +"' class='restrGroups'>"+ groupsfdb +"</div></td><td><div id='showGrps-"+ k +"' class='showAllGroups'><img src='/apps/sms_relentless/img/group.svg' style='cursor:pointer' title='Show all groups'></div></td><td><div id='rstusr-"+ k +"' class='restrUsers'>"+ usersfdb +"</div></td><td><div id='showUsr-"+ k +"' class='showAllUsers'><img src='/apps/sms_relentless/img/user.svg' style='cursor:pointer' title='Show all users'></div></td><td><img id='rmRow-"+ k +"' class='removeRow' src='/apps/sms_relentless/img/close.svg' title='Remove this row from the database' style='cursor:pointer;margin:6px 7px 0px 6px;'></td><td><input type='submit' id='rstsave-"+ k +"' class='saveRestrictions' value='Edit' title='Edit Row' /></td></tr>");
              }
              $("#phoneNmbrRestr").append("<div><img id='addRestrRow' src='/apps/sms_relentless/img/add.svg' title='Add Row'></div>");
          }


          // Get the available phone numbers from all providers associated with the access keys entered on the Settings page
          $("#phoneNumberTh").addClass('icon-loading');
          var getnumbersUrl = OC.generateUrl("/apps/sms_relentless/user/getsmsnumbers");
          var numbersListItems = '';

	  $.ajax({
		  url: getnumbersUrl + '/' + userid,
		  type: "POST",
		  cache: false,
		  processData: false,
		  contentType: false,
		  success: function(currentnmbrs) {

                                    $("#phoneNumberTh").removeClass('icon-loading');

				    // Create a list with all the available phone numbers
                                    numbersListItems = "<option value='' selected>Select phone number</option>";

				    $.each(currentnmbrs, function(key, indsmsnmb) {
					 var emptyinit = indsmsnmb.split(":");
					 var emptysec = emptyinit[1];
					 var emptycheck = emptysec.replace(" ", "").replace("+", "");

					 if (emptycheck != '') {
					     numbersListItems += "<option value='"+ indsmsnmb +"'>"+ indsmsnmb +"</option>";
					 }
				    });

				    if (restrNmb == 0) { var indRow = 0; } else { var indRow = parseInt(restrNmb + 1); }

				    // Append the list of available phone numbers
				    $("#rstphn-"+ indRow).empty();
				    $("#rstphn-"+ indRow).append(numbersListItems);
        
		  },
		  error: function() {
                                    $("#phoneNumberTh").removeClass('icon-loading'); 
                                    alert("Error while attempting to retrieve the available phone numbers!");
                  }
          });


          // Create a list with all the available groups
          var grpsListItems = "";
          $.each(allGroups, function(key, value) {
                 grpsListItems += "<div class='groupsList'>"+ value.gid +"</div>";
          });

          // Create a list with all the available users
          var usersListItems = "";
          $.each(allUsers, function(key, usrval) {
                 usersListItems += "<div class='usersList'>"+ usrval.value +"</div>";
          });


          function showLists() {

              // Append the list of available groups
              $('[id^="showGrps-"]').click(function() {
                 var crtnmbr = $(this).attr("id").replace("showGrps-", "");
                 $("#grpL-"+ crtnmbr).remove();
                 $("#showGrps-"+ crtnmbr).append("<div id='grpL-"+ crtnmbr +"' class='grpsList'>"+ grpsListItems +"</div>");
                 $("#adminOverlay").remove();
                 $("#admin_conf").append("<div id='adminOverlay'></div>");

                 $("#adminOverlay").click(function() { 
                    $("#adminOverlay").remove(); 
                    $("#grpL-"+ crtnmbr).remove(); 
                    $("#usrL-"+ crtnmbr).remove();
                 });

                 // Select a group
                 $(".groupsList").click(function() {
                    var slctdGrp = $(this).text();
                    $("#grpL-"+ crtnmbr).remove();
                    var addedTxtgrp = $("#rstgrp-"+ crtnmbr).text();

                    if (addedTxtgrp.indexOf(slctdGrp) == -1) {
                        $("#rstgrp-"+ crtnmbr).append("<div class='selectedGrps'>"+ slctdGrp +"<img id='rmvGrp-"+ slctdGrp +"' class='removeGroup' src='/apps/sms_relentless/img/close.svg' title='Remove this group'></div>");
                    } else { alert("That group has already been added!"); }

                    // Remove a group from list
                    $('[id^="rmvGrp-"]').click(function() {
                       $(this).closest(".selectedGrps").remove();
                    });
                 });

              });

              // Append the list of available users
              $('[id^="showUsr-"]').click(function() {

                 var ctusrnmbr = $(this).attr("id").replace("showUsr-", "");
                 $("#usrL-"+ ctusrnmbr).remove();
                 $("#showUsr-"+ ctusrnmbr).append("<div id='usrL-"+ ctusrnmbr +"' class='usrsList'>"+ usersListItems +"</div>");
                 $("#adminOverlay").remove();
                 $("#admin_conf").append("<div id='adminOverlay'></div>");

                 $("#adminOverlay").click(function() { 
                    $("#adminOverlay").remove(); 
                    $("#grpL-"+ ctusrnmbr).remove(); 
                    $("#usrL-"+ ctusrnmbr).remove();
                 });

                 // Select a user
                 $(".usersList").click(function() {
                    var slctdUsr = $(this).text();
                    var addedTxtusr = $("#rstusr-"+ ctusrnmbr).text();

                    if (addedTxtusr.indexOf(slctdUsr) == -1) {
                        $("#rstusr-"+ ctusrnmbr).append("<div class='selectedUsrs'>"+ slctdUsr +"<img id='rmvUsr-"+ slctdUsr +"' class='removeUser' src='/apps/sms_relentless/img/close.svg' title='Remove this user'></div>");
                    } else { alert("That user has already been added!"); }

                    // Remove a user from list
                    $('[id^="rmvUsr-"]').click(function() {
                       $(this).closest(".selectedUsrs").remove();
                    });
                 });

              });

              // Remove a group from list
              $('[id^="rmvGrp-"]').click(function() {
                 $(this).closest(".selectedGrps").remove();
              });

              // Remove a user from list
              $('[id^="rmvUsr-"]').click(function() {
                 $(this).closest(".selectedUsrs").remove();
              });

          }
          showLists();


          // Save the data
          function saveRestrRow() {
             $('[id^="rstsave-"]').unbind("click");
             $('[id^="rstsave-"]').click(function(event) {

                 event.preventDefault();
                 var crntrwnmbr = $(this).attr("id").replace("rstsave-", "");

                 if ($(this).attr("value") == "Save") {

                     var phoneNmbr = $("#rstphn-"+ crntrwnmbr).val();
                     var slctdGroups = [];
                     $("#rstgrp-"+ crntrwnmbr +" .selectedGrps").each(function() {
                        slctdGroups.push($(this).text());
                     });
                     var slctdUsers = [];
                     $("#rstusr-"+ crntrwnmbr +" .selectedUsrs").each(function() {
                        slctdUsers.push($(this).text());
                     });

                     if (phoneNmbr != '') {

                       if (slctdGroups.length > 0 || slctdUsers.length > 0) {

                         var saveRestrUrl = OC.generateUrl('/apps/sms_relentless/user/updatenumberrestrictions');
                         var datatosend = { 
                              userId: userid,
                              savedByDsplname: crntadmDispName,
                              phoneNumber: phoneNmbr,
                              groups: slctdGroups,
                              users: slctdUsers
                         };

	                 $.ajax({
	                   method: 'PUT',
	                   url: saveRestrUrl + '/' + userid,
	                   contentType: 'application/json',
	                   data: JSON.stringify(datatosend),
                           success: function(messagetosend) {
                                        if (messagetosend == 'success') {
                                            alert('The restrictions have been successfully saved to the database!');
                                        } else {
                                            alert('Error while trying to save the restrictions!');
                                        }
                           },
	                   error: function() {
		                        alert('Error while attempting to save the restrictions! You can check the Nextcloud log to find more details about this issue.');
	                   }
	                 });

                       } else { alert("You must select at least a group or a user in order to restrict the use of a phone number."); return; }

                     } else { alert("Please select a phone number!"); return; }

                     $(this).attr("value", "Edit");

                } else {

                     $("#rstsave-"+ crntrwnmbr).attr("value", "Save");
                }

             });
          }
          saveRestrRow();

          // Remove a row
          function removeRestrRow() {
               $('[id^="rmRow-"]').click(function() {

                  var slctRowRmv = $(this).attr("id").replace("rmRow-", "");
                  var crntPhNmbr = $("#rstphn-"+ slctRowRmv).val();

                  if (confirm("Do you really want to remove this row from the database ?")) {

                      var rmvRestrUrl = OC.generateUrl('/apps/sms_relentless/user/removenumberrestrictions');
                      $.ajax({
                           url: rmvRestrUrl + '/' + userid,
                           method: "POST",
                           dataType: "text",
                           data: { phoneNumber: crntPhNmbr },
                           success: function(delresult) {

                                             if (delresult.indexOf("success") > -1) {
                                                 alert("The restriction has been removed successfully!");
                                                 $("#rstphn-"+ slctRowRmv).closest("tr").remove();
                                             } else {
                                                 alert("Error while trying to remove restriction data!");
                                             }
                           },
                           error: function() { alert("Error while attempting to remove restriction data! You can check the Nextcloud log to find more details about this issue."); }
                       });
                  }
               });
          }
          removeRestrRow();

          // Add a new row
	  $("#addRestrRow").click(function() {
              if ($("#phoneNmbrRestr").find("tr:last-child").find(".restrPhoneNmbr").length > 0) {
                  var lastrstAuth = $("#phoneNmbrRestr").find("tr:last-child").find(".restrPhoneNmbr").attr("id").replace("rstphn-", "");
                  var indRowAdd = parseInt(lastrstAuth + 1);
              } else { var indRowAdd = 0; }
	      $("#phoneNmbrRestr").append("<tr><td><input type='text' class='restrAuthor' value='"+ crntadmDispName +"' disabled></td><td><select id='rstphn-"+ indRowAdd +"' class='restrPhoneNmbr'>"+ numbersListItems +"</select></td><td><div id='rstgrp-"+ indRowAdd +"' class='restrGroups'></div></td><td><div id='showGrps-"+ indRowAdd +"' class='showAllGroups'><img src='/apps/sms_relentless/img/group.svg' style='cursor:pointer' title='Show all groups'></div></td><td><div id='rstusr-"+ indRowAdd +"' class='restrUsers'></div></td><td><div id='showUsr-"+ indRowAdd +"' class='showAllUsers'><img src='/apps/sms_relentless/img/user.svg' style='cursor:pointer' title='Show all users'></div></td><td><img id='rmRow-"+ indRowAdd +"' class='removeRow' src='/apps/sms_relentless/img/close.svg' title='Remove this row from the database' style='cursor:pointer;margin:6px 7px 0px 6px;'></td><td><input type='submit' id='rstsave-"+ indRowAdd +"' class='saveRestrictions' value='Save' title='Save Row' /></td></tr>");
              showLists();
              saveRestrRow();
              removeRestrRow();

              // Check if the same phone number has been already restricted
              $("#rstphn-"+ indRowAdd).change(function() {
                 var selectedPhNmbr = $("#rstphn-"+ indRowAdd).val();
                 var allPHoneRestr = $("#phoneNmbrRestr").find("tr").find(".restrPhoneNmbr");
                 var phNmbrChck = 0;
                 allPHoneRestr.each(function() {
                    var slctdphnmbr = ($(this).val())? $(this).val() : $(this).text();
                    if (selectedPhNmbr == slctdphnmbr) { phNmbrChck++; }
                 });

                 if (phNmbrChck == 2) {
                     alert("This phone number is already in the list of restricted phone numbers. Please edit its own row, or choose a different phone number to restrict.");
                     $(this).val('');
                     return;
                 }
              });
	  });

     },
     error: function() {
                alert('Error while getting the admin settings! You can check the Nextcloud log to find more details about this issue.');
     }
  });


  $("#save_admin_settings").on("click", function(event) {

    event.preventDefault();
    OC.msg.startAction('#smsr_save_msg', t('sms_relentless', 'Saved'));

    var baseUrl = OC.generateUrl('/apps/sms_relentless/user/updateadminsettings');

    var showallmsgs = 0;
    if ($("#showallmessages").is(':checked')) {
        showallmsgs = 1;
    }

    var datatosave = {
                      userId: userid,
                      showAllMessages: showallmsgs
    };

    $.ajax({
       method: 'PUT',
       url: baseUrl + '/' + userid,
       contentType: 'application/json',
       data: JSON.stringify(datatosave),
       error: function(resp) {
                 alert('Error while attempting to save the settings! You can check the Nextcloud log to find more details about this issue.');
       }
    });
  });
});
