var client = null;
document.addEventListener("DOMContentLoaded", function(event) {
	client = new TVox.Client({
		url: 'tvox domain' //please, insert here your domain
	});
	
	globalUsername= null;
	
	toggleForm(client.state == 'LOGIN_REQUIRED');
	
	subscribeToLoginStateEvents();
	subscribeToCallsEvents();
	eventListenersUI();
	eventListenersCallButtonsUI();
	call1 = null;
	call2 = null;
	document.getElementById('container_call_2').style.display ='none';
	document.getElementById('container_call_1').style.display ='none';
});

function eventListenersCallButtonsUI(){
	// ------------------------------- ACTION PER CALL ---------------------------
	document.getElementById('answerButton1').addEventListener('click', ()=>{
		console.log('answer clicked for call 1');
			answerCall('1');
	});
	document.getElementById('answerButton2').addEventListener('click', ()=>{
		console.log('answer clicked for call 2');
			answerCall('2');
		});
	document.getElementById('dropButton1').addEventListener('click', ()=>{
		console.log('drop clicked for call 1');
			dropCall('1');
	});
	document.getElementById('dropButton2').addEventListener('click', ()=>{
		console.log('drop clicked for call 2');
			dropCall('2');
		});
	document.getElementById('holdButton1').addEventListener('click', ()=>{
		console.log('hold clicked for call 1');
			toggleHold('1', true);
	});
	document.getElementById('holdButton2').addEventListener('click', ()=>{
		console.log('hold clicked for call 2');
			toggleHold('2', true);
		});
	document.getElementById('unholdButton1').addEventListener('click', ()=>{
		console.log('unhold clicked for call 1');
			toggleHold('1',false);
	});
	document.getElementById('unholdButton2').addEventListener('click', ()=>{
		console.log('unhold clicked for call 2');
			toggleHold('2', false);
		});

	document.getElementById('transferButton1').addEventListener('click', ()=>{
		console.log('transfer clicked for call 1');
			transfCall('1');
	});
	document.getElementById('transferButton2').addEventListener('click', ()=>{
		console.log('tranfer clicked for call 2');
			transfCall('2');
	});
	
	// ------------------------------- DTMF PER CALL 1 ---------------------------
	
	document.getElementById('dtmf1_1').addEventListener('click', ()=>{
		console.log('dtmf 1 clicked for call 1');
			sendDTMF('1','1');
	});
	document.getElementById('dtmf2_1').addEventListener('click', ()=>{
		console.log('dtmf 2 clicked for call 1');
			sendDTMF('1','2');
	});
	document.getElementById('dtmf3_1').addEventListener('click', ()=>{
		console.log('dtmf 3 clicked for call 1');
			sendDTMF('1','3');
	});
	document.getElementById('dtmf4_1').addEventListener('click', ()=>{
		console.log('dtmf 4 clicked for call 1');
			sendDTMF('1','4');
	});
	document.getElementById('dtmf5_1').addEventListener('click', ()=>{
		console.log('dtmf 5 clicked for call 1');
			sendDTMF('1','5');
	});
	document.getElementById('dtmf6_1').addEventListener('click', ()=>{
		console.log('dtmf 6 clicked for call 1');
			sendDTMF('1','6');
	});
	document.getElementById('dtmf7_1').addEventListener('click', ()=>{
		console.log('dtmf 7 clicked for call 1');
			sendDTMF('1','7');
	});
	document.getElementById('dtmf8_1').addEventListener('click', ()=>{
		console.log('dtmf 8 clicked for call 1');
			sendDTMF('1','8');
	});
	document.getElementById('dtmf9_1').addEventListener('click', ()=>{
		console.log('dtmf 9 clicked for call 1');
			sendDTMF('1','9');
	});
	document.getElementById('dtmf0_1').addEventListener('click', ()=>{
		console.log('dtmf 0 clicked for call 1');
			sendDTMF('1','0');
	});
	document.getElementById('dtmf*_1').addEventListener('click', ()=>{
		console.log('dtmf * clicked for call 1');
			sendDTMF('1','*');
	});
	document.getElementById('dtmf#_1').addEventListener('click', ()=>{
		console.log('dtmf # clicked for call 1');
			sendDTMF('1','#');
	});
	
		
	// ------------------------------- DTMF PER CALL 2 ---------------------------	
	document.getElementById('dtmf1_2').addEventListener('click', ()=>{
		console.log('dtmf 1 clicked for call 2');
			sendDTMF('2','1');
	});
	document.getElementById('dtmf2_2').addEventListener('click', ()=>{
		console.log('dtmf 2 clicked for call 2');
			sendDTMF('2','2');
	});
	document.getElementById('dtmf3_2').addEventListener('click', ()=>{
		console.log('dtmf 3 clicked for call 2');
			sendDTMF('2','3');
	});
	document.getElementById('dtmf4_2').addEventListener('click', ()=>{
		console.log('dtmf 4 clicked for call 2');
			sendDTMF('2','4');
	});
	document.getElementById('dtmf5_2').addEventListener('click', ()=>{
		console.log('dtmf 5 clicked for call 2');
			sendDTMF('2','5');
	});
	document.getElementById('dtmf6_2').addEventListener('click', ()=>{
		console.log('dtmf 6 clicked for call 2');
			sendDTMF('2','6');
	});
	document.getElementById('dtmf7_2').addEventListener('click', ()=>{
		console.log('dtmf 7 clicked for call 2');
			sendDTMF('2','7');
	});
	document.getElementById('dtmf8_2').addEventListener('click', ()=>{
		console.log('dtmf 8 clicked for call 2');
			sendDTMF('2','8');
	});
	document.getElementById('dtmf9_2').addEventListener('click', ()=>{
		console.log('dtmf 9 clicked for call 2');
			sendDTMF('2','9');
	});
	document.getElementById('dtmf0_2').addEventListener('click', ()=>{
		console.log('dtmf 0 clicked for call 2');
			sendDTMF('2','0');
	});
	document.getElementById('dtmf*_2').addEventListener('click', ()=>{
		console.log('dtmf * clicked for call 2');
			sendDTMF('2','*');
	});
	document.getElementById('dtmf#_2').addEventListener('click', ()=>{
		console.log('dtmf # clicked for call 2');
			sendDTMF('2','#');
	});
}

function transfCall(idx, blind = false, numToBlind = ''){
	if(!blind && call1 !== null && call2 !== null){
		if(idx =='1') {
			call1.transferToCall(call2).then((result) =>{
				console.log('attended transfer call1 with call2 result: ' + result);
			});
		} else {
			call2.transferToCall(call1).then((result) =>{
				console.log('attended transfer call2 with call1 result: ' + result);
			});
		}
	}
	if(blind && numToBlind != ''){
		if(idx =='1') {
			call1.transferToNumber(numToBlind).then((result) =>{
			console.log('transfer blind call1 with number result: ' + result);
			});
		} else {
			call2.transferToNumber(numToBlind).then((result) =>{
				console.log('transfer blind call2 with number result: ' + result);
			});
		}
	}
}

function sendDTMF(idx, value){
	if(idx =='1') {
		call1.sendDTMF(value).then((result) =>{
			console.log('answer result: ' + result);
		});
	} else {
		call2.sendDTMF(value).then((result) =>{
			console.log('answer result: ' + result);
		});
	}
}

function answerCall(idx){
	if(idx =='1') {
		call1.answer().then((result) =>{
			console.log('answer result: ' + result);
		});
	} else {
		call2.answer().then((result) =>{
			console.log('answer result: ' + result);
		});
	}
}

function toggleHold(idx, setHold){
	if(idx =='1' && setHold) {
		call1.hold().then((result) =>{
			console.log('hold result: ' + result);
		});
	} 
	if(idx =='1' && !setHold) {
		call1.unhold().then((result) =>{
			console.log('unhold result: ' + result);
		});
	} 
	
	if(idx =='2' && setHold) {
		call2.hold().then((result) =>{
			console.log('hold result: ' + result);
		});
	} 
	if(idx =='2' && !setHold) {
		call2.unhold().then((result) =>{
			console.log('unhold result: ' + result);
		});
	} 
}
function dropCall(idx){
	if(idx =='1') {
		call1.terminate().then((result) =>{
			console.log('terminate result: ' + result);
		});
	} else {
		call2.terminate().then((result) =>{
			console.log('terminate result: ' + result);
		});
	}
}


function eventListenersUI(){
	// listener for UI
	// login button
	document.getElementById('loginButton').addEventListener('click', ()=>{
		loginUser()
	});
	// logout button
	document.getElementById('logoutButton').addEventListener('click', ()=>{
		logoutUser()
	});
	// dial button
	document.getElementById('dialButton').addEventListener('click', () =>{
		dialNumber();
	});
	//search button
	document.getElementById('searchButton').addEventListener('click', () =>{
		searchContacts();
	});
	//load call history
	document.getElementById('loadCallHistoryButton').addEventListener('click', () =>{
		loadCallHistory();
	});
	
	
}

function subscribeToCallsEvents(){
	// subscribe to event newcall to receive calls information
	client.phone.on('newcall', (call) => {
		console.log('event: received new call: ',call);
		//manage only sip call
		if(call.type == 'SIP'){
			// call is a CallSip instance
			console.log('my currentcall: ', call);
			if(call1== null){
				call1= call;
				updateInfoForCall('1', true);
			} else {
				if(call2 == null) {
				call2= call;
				updateInfoForCall('2', true);
				} else {
					console.warn('just have 2 calls in progress');
				}
			}
		} else {
			// call is a CallWebrtc instance	
			//nothing to do at the moment
		}
		//subscribe to call events
		call.on("accepted", function(){
		 console.log("call event - call accepted with callId "+ call.lookup.display.number);
		 })
		.on("ended", function() {
			//event for ended call: go to update objects and calls UI
			console.error("call event - ended", call);
			if(call1 && call.id == call1.id){
				 call1 = null;
				 updateInfoForCall('1', false);
			}
			if(call2 && call.id == call2.id) {
				 call2 = null;
				 updateInfoForCall('2', false);
			}
			if(call2 != null && call1 == null){
				call1 = call2;
				updateInfoForCall('1', true);
				call2 = null;
				updateInfoForCall('2', false);	
			}
		 })
		.on("change_features", function(features) {
			//event for call features changed: go to update call buttons bar
			console.log("call event  - new features", features, call);
			if(call1 && call1.id == call.id){
				updateButtonsFromFeatures('1', call);
			}
			if(call2 && call2.id == call.id){
				updateButtonsFromFeatures('2', call);
			} 
		 });
	});
}

function subscribeToLoginStateEvents(){
	// subscribe to login event
	client.on('logged_in', () => {
		// user is logged in the client
		console.log('event: logged in');
		document.getElementById('loginEvent').innerHTML ='Logged in';
		document.getElementById('loginButton').disabled = true;
		updateUserInfoLogged('User logged: '+ client.user.info.username);
	})
	.on('logged_out', () => {
		// user is logged out from the client
		console.log('event: logged out');
		toggleForm(true);
		document.getElementById('loginEvent').innerHTML ='Logged out';
		document.getElementById('loginButton').disabled = false;
		updateUserInfoLogged('User logged out: '+ client.user.info.username);		
	})
	.on('login_in_progress', () => {
		// login for user is in progress.. waiting
		console.log('event: login in progress');
		document.getElementById('loginEvent').innerHTML ='Login in progress';
		document.getElementById('loginButton').disabled = true;
		updateUserInfoLogged('Login in progress for user: '+ globalUsername );		
	})
	.on('login_failed', () => {
		// login failed, update UI to show login form
		console.log('event: login failed');
		toggleForm(true);
		document.getElementById('loginEvent').innerHTML ='Logged failed, retry';
		document.getElementById('loginButton').disabled = true;
		updateUserInfoLogged('User failed for user: '+ client.user.info.username);		
	})
	.on("ready", function() {
		// user is ready to use 
        console.log("event: ready... client is ready to use");
		toggleForm(false);
		updateUserInfoLogged('Client ready for user: '+ client.user.info.username);
        // now we can use client attribute to interact with tvox
		updateUserProfileInformation(); //show info for profile: available profiles, profile in use etc..
    });
}

function updateUserProfileInformation(){
	//subscribe to profile_selected event, to have current profile logged
	client.user.on('profile_selected', (profile) =>{
		console.log('profile selected: ', profile);
		document.getElementById('selectedProfile').innerHTML ='<b>Profile selected: </b> '+profile.id+ ' ' + profile.label+ ' type: '+profile.type;
		document.getElementById('availableProfiles').innerHTML = '';
		console.log('profiles available ', client.user.availableProfile);
		// show all profiles available for current logged user
		for(const prof in client.user.availableProfile) {
			document.getElementById('availableProfiles').innerHTML += '<button onclick="useCurrProfile('+client.user.availableProfile[prof].id+')"> Use this profile!</button> '+ client.user.availableProfile[prof].id+ ' ' + client.user.availableProfile[prof].label+ ' type: '+client.user.availableProfile[prof].type+ ' <br/>';
		}
	});
}

function useCurrProfile(profileId){
	console.log('ask to use current profile: ',profileId);
	var profile = client.user.availableProfile.filter(obj => {
		return obj.id == profileId;
	});
	if(profile.length > 0){
		// method to use a new profile. must pass whole profile object
		client.user.useProfile(profile[0]); 
	} else {
		alert('Profile does not exists');
	}
}

function subscribeToCalls(){
	
}

function loadCallHistory() {
	//search call history items: first page with size 10
	client.user.getCallHistory({'pageNumber':1,'pageSize':10}).then(function(result) {
		let value = [];
   result
       .on("data", function(data, index, total){
             console.log("callHistory - result - DATA received: ", data);
			 if(value.length==0){
				 
			 value.push(data.data);
			 }
         })
      .on("error", function(error) {
             console.error("callHistory - result - ERROR");
         })
      .on("complete", function() {
             console.log("callHistory - result - COMPLETE");
         });
	});
}
// method to search contact
function searchContacts() {
	var textToSearch = document.getElementById("textToSearch").value;
	textToSearch = textToSearch.trim();
	// toSearch: text digited by user
	// pageNumber to search
	// pageSize: dimension of page
	client.user.searchContact({'pageNumber':1,'pageSize':10, 'toSearch':textToSearch})
	.then(function(result) {
		let value = [];
   result
       .on("data", function(data, index, total){
             console.log("searchContact - result - DATA", data);
			 if(value.length==0){
				 
			 value.push(data.data);
			 }
         })
      .on("error", function(error) {
             console.error("searchContact - result - ERROR");
         })
      .on("complete", function() {
             console.log("searchContact - result - COMPLETE");
         });
})
	.catch(function(error) {
     console.error("searchContact - ERROR", error);
});

}

function dialNumber(){
	var number = document.getElementById("numToDial").value;
	number = number.trim();
	if(number != "" && !isNaN(number)) {
		client.phone.device.dial(number);
	} else {
		alert('number not valid');
	}
}

function updateButtonsFromFeatures(idx, call){
	document.getElementById('holdButton'+idx).style.display = call.features.includes('HOLD') ? 'block' : 'none';
	document.getElementById('unholdButton'+idx).style.display = call.features.includes('UNHOLD') ? 'block' : 'none';	
	document.getElementById('dtmfBar'+idx).style.display = call.features.includes('GENERATE_DTMF') ? 'block' : 'none';	
	document.getElementById('transferButton'+idx).style.display = call.features.includes('TRANSFER_ATTENDED') ? 'block' : 'none';	
	document.getElementById('dropButton'+idx).style.display = call.features.includes('CANCEL') ? 'block' : 'none';
	document.getElementById('answerButton'+idx).style.display = call.features.includes('ANSWER') ? 'block' : 'none';
}

function updateInfoForCall(idx, show) {
	var call = idx == '1' ? call1 : call2;

	document.getElementById('container_call_'+idx).style.display = show? 'block' :'none';
	if(call) {
	document.getElementById('callDirection'+idx).innerHTML = 'direction: ' + call.direction;
	if(call.lookup.display.number){
		document.getElementById('number'+idx).innerHTML ='number: ' + call.lookup.display.number;
	}
	if(call.lookup.display.name){
	document.getElementById('displayName'+idx).innerHTML = 'name: ' + call.lookup.display.name;
	}
	if(call.lookup.display.company){
	document.getElementById('displayCompany'+idx).innerHTML ='company: ' + call.lookup.display.company;
	}
	
	updateButtonsFromFeatures(idx, call);
	}
	/*if(call.lookup.display.service){
		document.getElementById('serviceName'+idx).innerHTML ='service: ' + call.lookup.display.company;
	}*/
}	

function updateUserInfoLogged(label){
	document.getElementById('userInfoLogged').innerHTML = label;
}


function toggleForm(showLoginForm){
	if(showLoginForm){
		document.getElementById('loginForm').style.display= 'block';
		document.getElementById('logoutForm').style.display='none';
		document.getElementById('loggedSection').style.display='none';
	} else {
		document.getElementById('loginForm').style.display= 'none';
		document.getElementById('logoutForm').style.display= 'block';
		document.getElementById('loggedSection').style.display='block';
	}
}

function logoutUser(){
	client.logout();
}

function loginUser(){
	let username = document.getElementById("username").value;
	globalUsername = username;
	let password = document.getElementById("password").value;
  if (username == "" || password  == "") {
	document.getElementById('errorLogin').innerHTML ='username and password must be filled!!'
    return;
  }
  client.login({username: username,password: password}); //invoke login method
}