//CHARGEMENT DE LA PAGE
function init_plugin_factory(event){
	
	$('#factoryForm').on('keyup','input',factory_render);
	$('#factoryForm').on('keydown','input,select',factory_shortcut);
	$('#factoryForm').on('change','select',factory_render);
	$('#factoryParts').on('click','li a',function(){
		$('#factoryParts li a').removeClass('active');
		$(this).addClass('active');
		factory_render(event);
	});

	$('#factoryParts .nav-link.active').trigger('click');

	$('#plugin').autocomplete({
		action : 'factory_autocomplete_plugin',
		onClick : function(selected,element){
			$('#plugin').val(selected.name);
			console.log('click on '+selected.name);
			$.action({action:'factory_entity_search',plugin:selected.name},function(response){
				if(response.rows.length==0) return;
				var html = '<optgroup label="Entités">';
				for(var key in response.rows){
					html +='<option value="entity-'+response.rows[key]+'">'+response.rows[key]+'</option>';
				}
				html += '</optgroup>';
				$('.fieldType').append(html);
			});
			

			
		}
	});

	$('#entity').attr('autocomplete','off').typeahead({ 
		items: 5,
		minLength: 2,
		autoSelect : false,
		selectOnBlur : false,
		displayText : function(item){
			return  item.name || item;
		},
		source: function(keyword, response){
			$.action({
				action: 'factory_autocomplete_entity',
				keyword: $('#entity').val(),
				plugin: $('#plugin').val() 
			},function(r){
				if(r.rows != null)
					response(r.rows);
			});
		},
		matcher: function(r){
		    return '<div>'+r.name+'</div>';
		},
		afterSelect: function(item) {
			$('#entity').data('selected',true);
			$.action({
				action: 'factory_autocomplete_entity_select',
				entity: item.name,
				plugin: $('#plugin').val() 
			},function(r){
				$('#factoryForm .field:not(:eq(0))').remove();
				$('#factoryForm .field:eq(0) input').val(r.rows[0].label);
				$('#factoryForm .field:eq(0) select').val(r.rows[0].type);
				for(var k in r.rows){
					if(k==0) continue;
					factory_addline($('#factoryForm .field').eq(0),r.rows[k]);
				}
				factory_render();
			});
      	}
	});




}

function factory_change_template(event){
	factory_search_part();
	factory_search_filters();
	event.stopPropagation();
}


function factory_shortcut(event){
	if(this.id=='entity' && event.keyCode==9){
		event.preventDefault();
		$('#factoryForm .field:eq(0) input:eq(0)').focus();
	}

	if($(this).hasClass('fieldType') && event.keyCode==9){
		event.preventDefault();
		return factory_addline(this);
	}

	if(event.keyCode == 107){
		event.preventDefault();
		return factory_addline(this);
	}
	if(event.keyCode == 109){
		event.preventDefault();
		return factory_removeline(this);
	}
}



function factory_search_part(callback){
	$('#factoryParts').fill({
		action : 'factory_search_part',
		template : $('#template').val()
	},
	function(){
		if(callback) callback();
	});
}

function factory_search_filters(callback){
	$('#factoryFilters ul').fill({
		action : 'factory_search_filters',
		template : $('#template').val(),
		part : $('#factoryParts li a.active').attr('data-part'),
	},
	function(){
		if($('#factoryFilters ul li:visible').length!=0){
			$('#factoryFilters h4').removeClass('hidden');
		}else{
			$('#factoryFilters h4').addClass('hidden');
		}
		$('#factoryFilters input[data-checked="checked"]').prop('checked',true);
		if(callback) callback();
	});
}

function factory_render(event,generate){
	if(generate)
		if(!confirm("Souhaitez-vous générer le fichier associé à l'onglet courant ?\nSi le fichier existe déjà, il sera écrasé.")) return;
	var data = $('#factoryForm').toJson();
	data.part = $('#factoryParts li a.active').attr('data-part');
	if(!data.part) return;
	data.template = $('#template').val();
	data.fields = {};
	$('#factoryForm .field').each(function(i,line){
		data.fields[$('.fieldSlug',line).val()] = {type:$('.fieldType',line).val(),label:$('.fieldLabel',line).val()} ;
	});

	data.filters = [];
	$('#factoryFilters li:visible input:checked').each(function(i,line){
		data.filters.push($(line).attr('data-section')) ;
	});

	data.generate = generate ? 1 : 0;
	$('#factoryCode').load('action.php?action='+data.action,data,function(){
		if(generate) $('#factory-generate-message').text("Fichier "+data.part+" généré");

		$('#factoryCode').attr('class',$('#factoryParts li a.active').attr('data-langage')) ;
	    hljs.highlightBlock($('#factoryCode').get(0));
	});
}

function factory_addline(element,data){
	var line = $(element).closest('.field');
	var newline = $(line).clone();
	newline.find('input').val('');
	$(line).after(newline);
	newline.find('input:eq(0)').focus();

	if(data){
		newline.find('input').val(data.label);
		newline.find('select').val(data.type);
	}
}

function factory_removeline(element){
	var line = $(element).closest('.field');
	if($('.field').length==1){
		line.find('input').val('');
		line.find('input:eq(0)').focus();
	}else{
		prevline = line.prev('.field');
		line.remove();
		prevline.find('input:eq(0)').focus();
	}
	
}