var videoPreview;
var mediaRecorder;
var recordedChunks = [];
 
//CHARGEMENT DE LA PAGE
function init_plugin_screenshare(){
	switch($.urlParam('page')){
		default:
		break;
	}
	videoPreview = $("#screenshare-preview").get(0);
	$('#screen-videos').sortable_table({
		onSort : screenshare_screen_video_search
	});
}


//Enregistrement des configurations
function screenshare_setting_save(){
	$.action({ 
		action : 'screenshare_setting_save', 
		fields :  $('#screenshare-setting-form').toJson() 
	},function(){ $.message('info','Configuration enregistrée'); });
}


/** SCREENVIDEO **/

function screenshare_screen_mouse_toggle(){
	var mouseButton = $('.mouse-button');
	if(mouseButton.attr('data-mode') == 'active'){
		mouseButton.attr('data-mode','inactive');
	}else{
		mouseButton.attr('data-mode','active');
	}
}
function screenshare_screen_sound_toggle(){
	var soundButton = $('.sound-button');
	if(soundButton.attr('data-mode') == 'active'){
		soundButton.attr('data-mode','inactive');
	}else{
		soundButton.attr('data-mode','active');
	}
}

async function screenshare_screen_video_record() {
 var button = $('.record-button');
 var mouseButton = $('.mouse-button');
 var soundButton = $('.sound-button');
 if(button.attr('data-mode') == 'recording')
 {
 	//arret de capture
 	button.attr('data-mode','');
 	button.find('i').removeClass('far fa-circle').addClass('fas fa-circle');
 	mediaRecorder.stop();
	var tracks = videoPreview.srcObject.getTracks();
	tracks.forEach(track => track.stop());
	videoPreview.srcObject = null;
 }else{
 	//démarrage de capture
 	button.attr('data-mode','recording');
 	button.find('i').removeClass('fas fa-circle').addClass('far fa-circle');

 	try {
 		var options={
	      video: {
	         cursor: mouseButton.attr('data-mode') == 'active' ? "always" : "never"
	      },
	      audio: soundButton.attr('data-mode') == 'active'
	    };
	   
	    stream = await navigator.mediaDevices.getDisplayMedia(options);
	    
	    mediaRecorder = new MediaRecorder(stream, { mimeType: "video/webm; codecs=vp9" });
	    mediaRecorder.ondataavailable = screenshare_screen_video_recording;
	    
	    stream.getVideoTracks()[0].onended  = function(){ screenshare_screen_video_record(); };
	    mediaRecorder.start();
	    videoPreview.srcObject =stream;
	  } catch(error) {
	  	console.log("'"+error+"'");
	  	button.attr('data-mode','');
	  	button.find('i').removeClass('far fa-circle').addClass('fas fa-circle');
	  	if(""+error.toString()!='NotAllowedError: Permission denied')
	  		$.message('error','Erreur lors de l\'enregistrement '+JSON.stringify(error));
	  }
 }

}

function screenshare_screen_video_progress(mode){
	if(mode){
		$('.screenshare-progress').removeClass('hidden');
	}else{
		$('.screenshare-progress').addClass('hidden').find('>span').text('');
		$('.screenshare-progress').find('.progress progress-bar').css('width','0%');
	}
}

function screenshare_screen_video_recording(event) {

	  screenshare_screen_video_progress(true);

	  if (event.data.size > 0) {
	    recordedChunks.push(event.data);
	    var blob = new Blob(recordedChunks, {
	    type: "video/webm"
	  });

	 var url = URL.createObjectURL(blob);
	 var filename = "capture.webm";
	 var data = new FormData();
	 data.append('name', filename);
	 data.append('tmp_name', url);
	 data.append('data', blob);
	 
	 //todo $.action
	var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
	xhr.open( 'post', 'action.php?action=screenshare_screen_video_save', true);
	
	var progress = $('#screenshare-progress .progress .progress-bar');
	var progressText = $('.screenshare-progress').find('>span');
	xhr.upload.addEventListener("progress", function(evt){
		if (evt.lengthComputable) {
		var percentComplete = (evt.loaded / evt.total) * 100;
		percentComplete = Math.round(percentComplete * 100) / 100;
		progress.css('width',percentComplete+'%');
		progressText.text(percentComplete+'%');
		}
	}, false);

	xhr.onreadystatechange = function () {
	  if(xhr.readyState === 4 && xhr.status === 200) {
	  	screenshare_screen_video_progress(false);
	    var response = xhr.responseText;
	    screenshare_screen_video_search();
	  }
	};
	xhr.send(data);

  }
}


//Récuperation d'une liste de screenvideo dans le tableau #screenvideos
function screenshare_screen_video_search(callback){
	
	var box = new FilterBox('#filters');	
	$('#screen-videos').fill({
		action:'screenshare_screen_video_search',
		filters : box.filters(),
		sort : $('#screen-videos').sortable_table('get')
	},function(response){
		$('.results-count span').text(response.pagination.total);
		init_components();
		if(callback!=null) callback();
	});
}

//Ajout ou modification d'élément screenvideo
function screenshare_screen_video_save(element){
	var li = $(element).closest('li');
	data.action = 'screenshare_screen_video_save';
	data.label = li.find('.label').val();
	data.expireHour = li.find('.expireHour').val();
	data.expireDate = li.find('.expireDate').val();
	data.id = li.attr('data-id');

	$.action(data,function(r){
		$.message('success','Enregistré');
	});
}

function screenshare_screen_video_preview(element){
	var line = $(element).closest('li');
	$("#screenshare-preview").attr('src',"action.php?action=screenshare_screen_video_preview&id="+line.attr('data-id'));
}


//Suppression d'élement screenvideo
function screenshare_screen_video_delete(element){
	if(!confirm('Êtes vous sûr de vouloir supprimer cet item ?')) return;
	var line = $(element).closest('li');
	$.action({
		action : 'screenshare_screen_video_delete',
		id : line.attr('data-id')
	},function(r){
		line.remove();
		$.message('info','Élement supprimé');
	});
}

