/**
 * @copyright 2021, 2024 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 stpappdir = 'apps';

   // Get app directory
   var getstpurl = OC.generateUrl('/apps/sip_trip_phone/user/getappdirectory');

   $.ajax({
     method: 'GET',
     url: getstpurl,
     contentType: 'application/json',
     success: function(stpappdirfdb) {
                   stpappdir = stpappdirfdb;

                   // Get the app's settings
                   var getsetUrl = OC.generateUrl('/apps/sip_trip_phone/user/getsettings');

		   $.ajax({
		      method: 'GET',
		      url: getsetUrl,
		      contentType: 'application/json',
		      success: function(settingsdb) {

			 var connectData = {
			      "User" : settingsdb.sipusername,
			      "Realm" : settingsdb.siprealm,
			      "Display" : settingsdb.pdisplayname,
			      "WSServer" : settingsdb.stphwssurl,
			      "Stun" : settingsdb.stunserver,
			      "Tracesipmsg" : settingsdb.tracesipmsg,
			      "Voicenumbers" : settingsdb.voicenumbers,
			      "Defaultvoicenumber" : settingsdb.defaultvoicenumber
			 };

			 localStorage.setItem('SIPCreds', JSON.stringify(connectData));

		         // Get the (voice call capable) phone numbers of the current user's contacts and of all the Nextcloud users who didn't hide their phone numbers
                         var getctpnUrl = OC.generateUrl('/apps/sip_trip_phone/user/getcontactsnmbrs');

			 $.ajax({
			      method: 'GET',
			      url: getctpnUrl,
			      contentType: 'application/json',
			      success: function(contactspndb) {

                                                 localStorage.setItem('NCContacts', JSON.stringify(contactspndb));


						 var getspswdUrl = OC.generateUrl('/apps/sip_trip_phone/user/getsippass');

						 $.ajax({
						      method: 'GET',
						      url: getspswdUrl,
						      contentType: 'text',
						      success: function(sippassword) {

							 if (!localStorage.getItem('SipTripPhone')) {

							     function generateAESKey(passphrase) {
								    const salt = CryptoJS.lib.WordArray.random(128 / 8);
								    const key256Bits = CryptoJS.PBKDF2(passphrase, salt, { keySize: 256 / 32, iterations: 100, });
								    return key256Bits;
							     }
							     function encryptAES(token, key) {
								    var token = CryptoJS.AES.encrypt(token, key);
								    return token.toString();
							     }
	                                                     var genPassphr = Date.now() + Math.floor(Math.random()*10000).toString(6).toUpperCase();
	                                                     var aesKey = String(generateAESKey(genPassphr));
	                                                     var encryptedTkn = encryptAES(sippassword, aesKey);
                                                             document.cookie = 'crsptknks='+ aesKey +'; max-age=30; path=/; samesite=strict; secure';
							     localStorage.setItem('sipUserToken', encryptedTkn);

							     // Open the phone window
                                                             var url = OC.generateUrl('/'+ stpappdir +'/sip_trip_phone/phone/index.php');
							     window.open(url, "SipTripPhone", "width=354,height=572,menubar=no,scrollbars=no,status=no,addressbar=no,resizable=no");

							 } else {
							     window.alert('The phone is already open!');
							 }
						      },
						      error: function() {}
						 });

		              },
		              error: function() { alert("An error occurred while getting the contacts. You can check the Nextcloud log to find more details about this issue."); }
		         });

		      },
                      error: function() { alert("An error occurred while getting the app's settings. You can check the Nextcloud log to find more details about this issue."); }
		   });

     },
     error: function() { alert("An error occurred while getting the app's directory. You can check the Nextcloud log to find more details about this issue."); }
   });

});
