//CHARGEMENT DE LA PAGE
function init_plugin_factory(event){

	$('#factoryForm').on('keyup','input',function(){
		//Evite le flood de render lorsqu'on tape un texte
		if(window.factoryRenderTimeout) clearTimeout(window.factoryRenderTimeout);
			window.factoryRenderTimeout = setTimeout(function(){
			factory_render();
		},300);
	});
	$('#factoryForm').on('change','#plugin-color,#plugin-icon',factory_render);
	$('#factoryForm').on('change','select',factory_render);

	$('#factoryForm').on('keydown','input,select',factory_shortcut);


	factory_change_template();

	$('#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.value);
			$('#pluginLabel').val(selected.label);
			$('#description').val(selected.description);
			$('#plugin-color').val(selected.color);
			$('#plugin-icon').val(selected.icon);
			init_components('#factoryForm');
		}
	});

	$('#plugin').focus();

	factory_entity_picker('#entity',function(element,r){
		$('#entityLabel').val(r.label);
		$('#factoryForm .field:not(:eq(0))').remove();

		var firstField = $('#factoryForm .field:eq(0)');
		$('.fieldSlug',firstField).val(r.rows[0].key);
		$('.fieldLabel',firstField).val(r.rows[0].label);
		$('.fieldType',firstField).val(r.rows[0].type);


		if(r.rows[0].link){
			$('.entity-picker',firstField).val(r.rows[0].link).removeClass('hidden');
			init_components(firstField);
		}

		for(var k in r.rows){
			if(k==0) continue;
			factory_addline(null,r.rows[k]);
		}
		factory_render();
	});


	$('#entity-fields').sortable({
		axis : 'y',
		handle : '.btn-move',
		update : function(){
			factory_render();
		}
	});

}

function factory_entity_picker(element,callback){
	var element = $(element);
	element.attr('autocomplete','off').typeahead({
		items: 5,
		minLength: 2,
		autoSelect : false,
		selectOnBlur : false,

		displayText : function(item){
			return '<span class="text-muted">'+item.parent+'/</span><span class="font-weight-bold">'+item.name+'</span>';

		},
		source: function(keyword, response){
			$.action({
				action: 'factory_autocomplete_entity',
				keyword: element.val(),
				plugin: element.is('[data-all-plugin]')? false : $('#plugin').val()
			},function(r){
				if(r.rows != null)
					response(r.rows);
			});
		},
		matcher: function(r){
		    return '<div>'+r.name+'</div>';
		},
		afterSelect: function(item) {
			element.data('selected',true);
			element.val(item.name);
			element.attr('data-path',item.path);
			$.action({
				action: 'factory_autocomplete_entity_select',
				entity: item.name,
				plugin: element.is('[data-all-plugin]')? false : $('#plugin').val()
			},function(r){
				if(callback) callback(element,r);
			});
      	}
	});
}

function factory_change_type(element){
	var select = $(element);
	var parent = select.parent();

	if(select.val()=='entity-external-entity'){
		var picker = parent.find('.entity-picker');
		picker.removeClass('hidden');
		picker.focus();
		init_components(picker.parent());
	}else{
		parent.find('.entity-picker').addClass('hidden');
	}
}

function factory_change_template(event){
	factory_search_part();
	factory_search_filters();

	if(event) 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(){
		factory_render();
		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="true"]').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){
		var field= {type:$('.fieldType',line).val(),label:$('.fieldLabel',line).val()} ;

		var entityPicker  = $(line).find('.entity-picker').val();
		if(entityPicker) field.entityPath = $(line).find('.entity-picker').val();
		data.fields[$('.fieldSlug',line).val()] = field;
	});

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

	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){

	if(element){
		var line = $(element).closest('.field');
		var newline = $(line).clone();
		newline.find('.entity-picker').addClass('hidden');
		newline.find('.data-type-entitypicker').remove();
		newline.find('input').val('');
		$(line).after(newline);
	}else{
		var line = $('#entity-fields .field:eq(0)');
		var newline = $(line).clone();
		newline.find('input').val('');
		$('#entity-fields').append(newline);
	}


	newline.find('input:eq(0)').focus();

	if(data){
		$('.fieldSlug',newline).val(data.key);
		$('.fieldLabel',newline).val(data.label);
		$('.fieldType',newline).val(data.type);

		if(data.link){
			$('.entity-picker',newline).val(data.link).removeClass('hidden');
		}else{
			$('.entity-picker',newline).val('').addClass('hidden');
		}
	}
}

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();
	}

}