/*
 * Daniele Callari 2017 www.daxtech.net
 */

Settings = {};
Settings.Init = function(){
	Settings.Load();
	$('#settingsResolution, #settingsFps, #settingsForcehevc, #settingsLocalaudio, #settingsRemote').bind('change', function(){
		Settings[ $(this).attr('data') ] = $(this).val();
		Settings.Save();
	});
};

Settings.Load = function(){
/*
		-720                    Use 1280x720 resolution [default]
        -1080                   Use 1920x1080 resolution
        -width <width>          Horizontal resolution (default 1280)
        -height <height>        Vertical resolution (default 720)
        -30fps                  Use 30fps
        -60fps                  Use 60fps [default]
        -bitrate <bitrate>      Specify the bitrate in Kbps
        -packetsize <size>      Specify the maximum packetsize in bytes
        -forcehevc              Use high efficiency video decoding (HEVC)
        -remote                 Enable remote optimizations
        -app <app>              Name of app to stream
        -nosops                 Don't allow GFE to modify game settings
        -localaudio             Play audio locally
        -surround               Stream 5.1 surround sound (requires GFE 2.7)
        -keydir <directory>     Load encryption keys from directory
*/
	Settings.resolution = (localStorage.getItem('resolution') == null)?'1280x720':localStorage.getItem('resolution');
	$('#settingsResolution').val(Settings.resolution);
	
	Settings.fps = (localStorage.getItem('fps') == null)?'60':localStorage.getItem('fps');
	$('#settingsFps').val(Settings.fps);

	Settings.forcehevc = (localStorage.getItem('forcehevc') == null)?'false':localStorage.getItem('forcehevc');
	$('#settingsForcehevc').val(Settings.forcehevc);

	Settings.localaudio = (localStorage.getItem('localaudio') == null)?'false':localStorage.getItem('localaudio');
	$('#settingsLocalaudio').val(Settings.localaudio);
	
	Settings.remote = (localStorage.getItem('remote') == null)?'false':localStorage.getItem('remote');
	$('#settingsRemote').val(Settings.remote);
	
	$('select').material_select();
}

Settings.Save = function(){
	localStorage.setItem('resolution'	, Settings.resolution);
	localStorage.setItem('fps'			, Settings.fps);
	localStorage.setItem('forcehevc'	, Settings.forcehevc);
	localStorage.setItem('localaudio'	, Settings.localaudio);
	localStorage.setItem('remote'		, Settings.remote);
	
	Materialize.toast("Configruation saved locally", 4000,'');
	console.log('Settings saved on local storage');
}

modal = function(params){

	params = $.extend({}, {
		id		: 'modal_'+Math.round(Math.random() * 100).toString(),
		ready 		: function(){},
		dismissible	: true,
		title		: 'Title',
		message		: 'Message',
		buttons		: {
			close : { label : 'Ok', callback: 'close' }
		}
	}, params);

	$('.modal').remove();
	
	var obj = 
		 '<div id="'+params.id+'" class="modal">'
		+	'<div class="modal-content">'
		+		'<h4>'+params.title+'</h4>'
		+		'<p>'+params.message+'</p>'
		+	'</div>'
		+	'<div class="modal-footer">';

		for ( key in params.buttons) {
			if (params.buttons.hasOwnProperty(key)) {
				if( params.buttons[key].callback == 'close' ){
					obj += '<a id="modal_action_'+key.toString()+'" href="#!" class="modal-action waves-effect modal-close waves-green btn-flat">'+params.buttons[key].label+'</a>';
				}else{
					obj += '<a id="modal_action_'+key.toString()+'" href="#!" class="modal-action waves-effect waves-green btn-flat">'+params.buttons[key].label+'</a>';
				}
			}
		}

		obj += '</div></div>';

		$('body').append(obj);

		for ( key in params.buttons) {
			if (params.buttons.hasOwnProperty(key)) {
				if( typeof(params.buttons[key].callback) == 'function' )  $('#modal_action_'+key.toString()).bind('click', params.buttons[key].callback );
				
			}
		}

		$('#'+params.id).modal({
			ready: params.ready,
			dismissible: params.dismissible
		}).modal('open');

		return $('#'+params.id);
};

function cpuLoad(){
	$.ajax({
		url		: 'api/cpuload.api.php',
		method 	: 'post',
		timeout	: 500
	}).done(function(s){
		vals = JSON.parse(s);
		
		$('#cpuValues').html(
			"<tr><td style='width: 15px; text-align: right'>1&nbsp;min</td><td class='number'><span style='background-color:#4CAF50;display:block;width:"+vals[0]+"%'>"+vals[0]+"%</span></tr>"
			+"<tr><td style='text-align: right'>5&nbsp;min</td><td class='number'><span style='background-color:#4CAF50;display:block;width:"+vals[1]+"%'>"+vals[1]+"%</span></tr>"
			+"<tr><td style='text-align: right'>15&nbsp;min</td><td class='number'><span style='background-color:#4CAF50;display:block;width:"+vals[2]+"%'>"+vals[2]+"%</span></tr>"
		);
		
	});
}

function ramLoad(){
	$.ajax({
		url		: 'api/ram-alloc.api.php',
		method 	: 'post',
		timeout	: 100
	}).done(function(s){
		vals = JSON.parse(s);
		
		$('#ramValue').html(
			"<tr><td style='width: 53px;'></td><td class='number'><span style='background-color:#4CAF50;display:block;width:"+vals.pc+"%'>"+vals.pc+"%</span></tr>"
			
		);
		
	});
}

function initpads(){
	
	var ok = function(){
		Materialize.toast("Running operation...", 4000,'');
		$.ajax({
			url: 'api/initPads.api.php',
			method : 'post'
		}).done(function(s){
			//console.log(s);
			$('#pads').modal('close');
			Materialize.toast("Done", 4000,'');
		});
		$('#pads').modal('close');
	};

	modal({
		id		: 'pads',
		title    : 'Init pads',
		message  : 'Do you really want re-init pads ?',
		buttons  : {
			close 	: { label: 'No', callback:'close' },
			dele 	: { label: 'Yes', callback: ok }
		}
	});
}


function unpair(){
	
	var ok = function(){
		Materialize.toast("Running operation...", 4000,'');
		$.ajax({
			url: 'api/unpair.api.php',
			method : 'post'
		}).done(function(s){
			console.log(s);
			
			modal({
				id		: 'done',
				title    : 'Done',
				message  : s,
				buttons  : {
					close 	: { label: 'Ok', callback:'close' }
				}
			});
			
		});
		$('#unpair').modal('close');
	};

	modal({
		id		: 'unpair',
		title    : 'Unpair',
		message  : 'Do you really want unpair server?',
		buttons  : {
			close 	: { label: 'No', callback:'close' },
			dele 	: { label: 'Yes', callback: ok }
		}
	});
}

function pair(){
	
	var ok = function(){
		Materialize.toast("Command sent, take a look in your pc...", 4000,'');
		$.ajax({
			url: 'api/pair.api.php',
			method : 'post'
		}).done(function(s){
			console.log(s);
			
			modal({
				id		: 'done',
				title    : 'Done',
				message  : s,
				buttons  : {
					close 	: { label: 'Ok', callback:'close' }
				}
			});
		});
		$('#pair').modal('close');
	};

	modal({
		id		: 'pair',
		title    : 'Pair',
		message  : 'Do you really want pair whit a server?',
		buttons  : {
			close 	: { label: 'No', callback:'close' },
			dele 	: { label: 'Yes', callback: ok }
		}
	});
}


function reboot(){
	
	var ok = function(){
		Materialize.toast("Running operation...", 4000,'');
		$.ajax({
			url: 'api/reboot.api.php',
			method : 'post'
		}).done(function(s){
			console.log(s);
			Materialize.toast("Rebooting...", 4000,'');
		});
		$('#reboot').modal('close');
	};

	modal({
		id		: 'reboot',
		title    : 'Reboot',
		message  : 'Do you really want reboot device ?',
		buttons  : {
			close 	: { label: 'No', callback:'close' },
			dele 	: { label: 'Reboot', callback: ok }
		}
	});
}

function stopStream(){
	
	var ok = function(){
		Materialize.toast("Running operation...", 4000,'');
		$.ajax({
			url: 'api/stopStream.api.php',
			method : 'post'
		}).done(function(s){
			console.log(s);
			Materialize.toast("Done", 4000,'');
		});
		$('#modal').modal('close');
	};
	
	
	modal({
		id		: 'modal',
		title    : 'Stop',
		message  : 'Do you really want to stop the stream?',
		buttons  : {
			close 	: { label: 'No', callback:'close' },
			dele 	: { label: 'Stop', callback: ok }
		}
	});
}

function poweroff(){
	
	var ok = function(){
		Materialize.toast("Running operation...", 4000,'');
		$.ajax({
			url: 'api/shutdown.api.php',
			method : 'post',
			timeout	: 3000
		}).done(function(s){
			console.log(s);
			Materialize.toast("Bye bye", 4000,'');
		});
		$('#modal').modal('close');
	};

	modal({
		id		: 'modal',
		title    : 'Shutdown',
		message  : 'Do you really want shutdown the system?',
		buttons  : {
			close 	: { label: 'No', callback:'close' },
			dele 	: { label: 'Shutdown', callback: ok }
		}
	});
}

function launch(game){
	
	var ok = function(){
		Materialize.toast("Running operation...", 4000,'');
		$.ajax({
			url: 'api/startgame.api.php',
			method : 'post',
			timeout	: 5000,
			data :{
				game       	: game,
				resolution 	: Settings.resolution,
				fps	   		: Settings.fps,
				forcehevc  	: Settings.forcehevc,
				localaudio 	: Settings.localaudio,
				remote		: Settings.remote
			}
		}).done(function(s){
			console.log(s);
			console.log(Settings);
			Materialize.toast("Done", 4000,'');
		});
		$('#modal').modal('close');
	};
	
	modal({
		id       : 'modal',
		title    : 'Start stream',
		message  : 'Do you really want start <b>' + game + '</b> ?' + "<br /><span style='font-size: 12px;'>"+Settings.resolution +' at ' + Settings.fps +" fps</span>",
		buttons  : {
			close 	: { label: "Abort", callback:'close' },
			ok 	: { label: 'Launch!', callback: ok }
		}
	});
}

function getGames(){
	$('#games').html(
		'<div style="width: 64px; padding-top: 100px; margin: 0 auto;">'
		+'  <div class="preloader-wrapper big active">'
		+'    <div class="spinner-layer spinner-blue-only">'
		+'      <div class="circle-clipper left">'
		+'        <div class="circle"></div>'
		+'      </div><div class="gap-patch">'
		+'        <div class="circle"></div>'
		+'      </div><div class="circle-clipper right">'
		+'        <div class="circle"></div>'
		+'      </div>'
		+'    </div>'
		+'  </div>'
		+'</div>'
		+'<div style="text-align: center;"><br />Detecting available applications...</div>'
	);
	
	$.ajax({ 
		url:'api/getGames.api.php'
	}).done(function(s){
		
		if(s.length > 4){
			var data = JSON.parse(s);
			
			$('#games').html('<ul class="collection" id="collection"> </ul>');
			Materialize.toast( data.length.toString() + ' applications found', 4000,'');
			$.each(data, function(n,o){
				//console.log(o);
				$('#collection').append(
				'<li class="collection-item avatar waves-effect" onclick=\'launch("'+o.name+'")\'>'
		 	    + 	'<i class="material-icons circle green">play_arrow</i>'
		  		+	'<span class="title">#'+o.id+'</span>'
			    +  	'<p>'+o.name+'</p>'
			    + '</li>'
     			);
			});
			
		}else{
			$('#games').html(
				'<div style="text-align: center;"><br /><i class="material-icons dp48">error_outline</i><br />No games detected<p>Maybe server is off or need to pair devices?</p></div>'
				+'<div style="text-align: center;"><br /><a class="waves-effect waves-light btn-large green" onclick="getGames()">Refresh</a></div>'
			);
		}
	});
}


$(document).ready(function(){
	
	Settings.Init();
	//$('select').material_select();
});
