var isProcessing = false;

function host_check_processing(){
	if(isProcessing){
		$('.machines-preloader').removeClass('hidden');
		$('.btn-search').addClass('btn-preloader');
	}else{
		 $('.machines-preloader').addClass('hidden');
	}
}


//CHARGEMENT DE LA PAGE
function init_plugin_host(){
	switch($.urlParam('page')){
		case 'plan':
			host_plan_search();
		break;
		case 'ping':
			host_application_url_search();
		default:
		break;
	}


	host_machine_search(function(){
		if(!$.urlParam('id')) return;
		var element = $('#machines > li[data-id="'+$.urlParam('id')+'"]');
		host_machine_edit(element.get(0));

	});

	$('#machines').sortable_table({
		onSort : host_machine_search
	});

	//Ajout de la fonction save sur les inputs classiques ET le dynamicForm
	$('.host-sheet-container').off('change').on('change', 'input, select', function(){
		if($(this).closest(".machine-application-container").length == 0)host_machine_save();
	});
	$('.host-sheet-container').off('blur').on('blur', 'textarea', function(){
		if($(this).closest(".machine-application-container").length == 0)host_machine_save();
	});
}



//Enregistrement des configurations
function host_setting_save(){
	$.action({
		action: 'host_setting_save',
		fields:  $('#host-setting-form').toJson()
	},function(){
		$.message('success','Enregistré');
	});
}

/** MACHINE / ENVIRONNEMENT **/
//Récuperation d'une liste  machine / environnement dans le tableau #machines
function host_machine_search(callback,exportMode){
	if(isProcessing) return;
	var box = new FilterBox('#filters');
	if(exportMode) $('.btn-export').addClass('btn-preloader');
	isProcessing = true;
	host_check_processing();

	$('#machines').fill({
		action:'host_machine_search',
		filters: box.filters(),
		sort: $('#machines').sortable_table('get'),
		export:  !exportMode ? false : exportMode
	},function(response){
		isProcessing = false;
		host_check_processing();
		if(!exportMode) $('.results-count span').text(response.pagination.total);
		if(callback!=null) callback();
	});
}

function host_application_url_search(){
	$('#vm-ping-list').fill({
		action:'host_application_url_search'
	});
}

function host_application_url_ping(){
	$('.ping-state').html('<i class="text-muted fas fa-circle-notch fa-spin"></i>');

	$('[data-application]').each(function(){
		var li = $(this);
		$.action({
			action : 'host_application_url_ping',
			application : li.attr('data-application')
		},function(response){

			var ping = response.ping;

			var state = '<i class="text-danger far fa-times-circle"></i>';
			if(ping.code == 200){
				state = '<i class="text-success far fa-check-circle"></i>';
			}

			li.find('.ping-state').html(state);
			li.find('.ping-message').html('<strong>'+ping.code+':</strong> '+ping.message);

		});
	});
}

function host_plan_search(){
	$.action({
		action:'host_plan_search',
		root:$('#root').val()
	},function(r){
		var table = $('#table-plan');
		var tpl = $('#table-plan-template').html();
		for(var k in r.rows){
			var machine = r.rows[k];
			var ip = machine.ip.split('.');
			if(ip.length<4) continue;
			ip = ip[3];
			var cell = table.find('td[data-ip='+ip+']');
			cell.html(Mustache.render(tpl,machine));
		}
	});
}

//Ajout ou modification machine / environnement
function host_machine_save(callback){
	var data = $('#machine-form').toJson();
	$('.host-preloader').removeClass('hidden');
	$.action(data,function(r){
		$('#machine-form').attr('data-id',r.id);
		$.urlParam('id',r.id);
		setTimeout(function(){
			$('.host-preloader').addClass('hidden');
		},500);
		if(callback) callback();
	});
}

//Récuperation ou edition machine / environnement
function host_machine_edit(element){
	var line = $(element).closest('.item-line');
	$('#machines >li').removeClass('active');
	line.addClass('active');
	$.action({
		action: 'host_machine_edit',
		id: line.attr('data-id')
	},function(r){
		$('.host-sheet-container').html(r.html);

		$.urlParam('id',r.id);

		init_components('#machine-form');
		$('#machine-form').readonly(r.readonly).attr('data-readonly',r.readonly);
	});
}

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

/** APPLICATION SUR LA MACHINE **/
//Récuperation d'une liste  application sur la machine dans le tableau #machineapplications
function host_machine_application_search(callback,exportMode){
	if(!$('#machine-form').attr('data-id')) return;
	var box = new FilterBox('#host_machine_application-filters');
	if(exportMode) $('.btn-export').addClass('btn-preloader');

	$('#machine-applications').fill({
		action:'host_machine_application_search',
		filters: box.filters(),
		machine : $('#machine-form').attr('data-id'),
		sort: $('#machine-applications').sortable_table('get'),
		export:  !exportMode ? false : exportMode
	},function(response){
		if(!exportMode) $('.results-count span').text(response.pagination.total);
		init_components('#machine-applications');
		if(callback!=null) callback();
	});
}

//Ajout ou modification application sur la machine
function host_machine_application_save(){
	var data = $('#machine-application-form').toJson();
	$('.host-preloader').removeClass('hidden');
	data.machine = $('#machine-form').attr('data-id');
	data.label = $('#machine-form [data-id="label"]').val();
	$.action(data,function(r){
		$('#machine-application-form').attr('data-id','');
		host_machine_application_search();
		$('#machine-application-form').attr('data-id',r.id);
		$.urlParam('id',r.id);
		$('.host-preloader').addClass('hidden');
	});
}

//Récuperation ou edition application sur la machine
function host_machine_application_edit(element){



	var editApplication = function(){
		var data = {
			action: 'host_machine_application_edit',
			machine : $('#machine-form').attr('data-id')
		};
		if(element){
			var line = $(element).closest('.item-line');
			$('#machine-applications li').removeClass('selected');
			line.addClass('selected');
			data.id = line.attr('data-id');
		}
		$.action(data,function(r){
			$('.host-application-container').html(r.html);
			init_components('.host-application-container');
			$('#machine-application-form #label').focus();
		});
	}

	//on s'assure que la fiche vm est enregistrée avant de créer
	//de nouvelles applications
	if(!$('#machine-form').attr('data-id')){
		host_machine_save(editApplication);
	}else{
		editApplication();
	}

}



//Suppression application sur la machine
function host_machine_application_delete(element,event){
	event.stopPropagation();
	if(!confirm('Êtes vous sûr de vouloir supprimer cet item ?')) return;
	var line = $(element).closest('.item-line');
	$.action({
		action: 'host_machine_application_delete',
		id: line.attr('data-id')
	},function(r){
		line.remove();
		$.message('info','Item supprimé');
	});
}


/** ACCèS à L'APPLICATION  **/
//Récuperation d'une liste  accès à l'application  dans le tableau #applicationaccesss
function host_application_access_search(callback,exportMode){
	var box = new FilterBox('#application_access_filters');
	if(exportMode) $('.btn-export').addClass('btn-preloader');

	$('#application-accesss').fill({
		action:'host_application_access_search',
		filters: box.filters(),
		sort: $('#application-accesss').sortable_table('get'),
		export:  !exportMode ? false : exportMode
	},function(response){
		if(!exportMode && response.pagination) $('.plugin-host-access-list .results-count span').text(response.pagination.total);
		if(callback!=null) callback();
	});
}

function host_application_access_page_search(element,event){

	if(event)event.stopPropagation();
	var line = $(element).closest('.item-line');
	var application = line.attr('data-id');
	if(!application) return;


	$('#machine-applications li').removeClass('selected');
	line.addClass('selected');

	var data = {
		action: 'host_application_access_search_page',
		export:false,
		application : application
	};


	$.action(data,function(r){
		$('.host-application-container').html(r.html);
		init_components('.host-application-container');
		$('#machine-application-form #label').focus();
	});
}

//Ajout ou modification accès à l'application
function host_application_access_save(){
	var data = $('#application-access-form').toJson();

	$.action(data,function(r){
		$('#application-access-form').clear().attr('data-id','');
		host_application_access_search();

		$('#application-access-form').attr('data-id',r.id);

		$.urlParam('id',r.id);
		$.message('success','Enregistré');
	});
}

//Récuperation ou edition accès à l'application
function host_application_access_edit(element){
	var line = $(element).closest('.item-line');

	$.action({
		action: 'host_application_access_edit',
		id: line.attr('data-id')
	},function(r){
		$('#application-access-form').fromJson(r);
		init_components('#application-access-form');
		$('#application-access-form').attr('data-id',r.id);
	});
}

//Suppression accès à l'application
function host_application_access_delete(element){
	if(!confirm('Êtes vous sûr de vouloir supprimer cet item ?')) return;
	var line = $(element).closest('.item-line');
	$.action({
		action: 'host_application_access_delete',
		id: line.attr('data-id')
	},function(r){
		line.remove();
		$.message('info','Item supprimé');
	});
}
