//CHARGEMENT DE LA PAGE
function init_plugin_hackpoint(){
	switch($.urlParam('page')){
		case 'sheet.sketch':
			if($('.hackpoint').hasClass('readonly')){
				$('.editable-input').attr('readonly','readonly');
				init_components();
			}
		break;
		case 'list.part':
			hackpoint_part_search();
		break;
		default:
		break;
	}
	
	$('#parts').sortable_table({
		onSort : hackpoint_part_search
	});
	
	$('#sketchs').sortable_table({
		onSort : hackpoint_sketch_search
	});

	hackpoint_resource_search();

}


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

//plugin jquery pour modale
$.fn.extend({
modalize : function(options){
		var obj = $(this);

		var o = $.extend({
			blur : null
		}, options);

		var overlay = $('.modalize-overlay');
		var modal = $('.modalize');
		if(overlay.length==0){
			overlay = $('<div class="modalize-overlay"></div>');
			modal = $('<div class="modalize bounceIn"></div>');
			$('body').append(overlay).append(modal);
		}

		var form = obj.detach();
		form.removeClass('hide');
		modal.html(form.get(0).outerHTML);
    	
    	var modalize = {
    		options : o,
    		modal : modal,
    		overlay : overlay,
    		hide : function(){
    			overlay.fadeOut();
				$(o.blur).removeClass('blur');
				modal.hide();
    		}
    	}

    	
    	modal.css('height',o.height?o.height+'px':'');


		modal.show();
		overlay.show();
		$(o.blur).addClass('blur');
		overlay.click(function(){
			modalize.hide();
		});

		return modalize;
	}
});

/** PART **/
	


//Récuperation d'une liste de part dans le tableau #parts
function hackpoint_resource_part_search(callback){
		
	$('#parts').fill({
		action:'hackpoint_resource_part_search',
		resource : $('#sketch-editor').attr('data-id'),
		showing : function(li,i){
			li.css('transform','scale(0)').removeClass('hidden');
			setTimeout(function(){
				li.css('transform','scale(1)');
			},i*200);
		}
	},function(){
		$('#parts li:not(:eq(0))').each(function(i,li){
			hackpoint_resource_part_upload(li);
			var div  = $('[data-stream]',li);
			if($(div).attr('data-stream') =='') return;
			$(div).css('background','url(data:'+$(div).attr('data-stream')+')')
		     	.css('background-size','cover');
		});

		if(callback!=null) callback();
	});
}


//Récuperation d'une liste de part dans le tableau #parts
function hackpoint_part_search(callback){
	
		
	$('#parts').fill({
		action:'hackpoint_part_search',
		resource : $('#sketch-editor').attr('data-id'),
	},function(){
		$('#parts li:not(:eq(0))').each(function(i,li){

			hackpoint_resource_part_upload(li);

			var div  = $('[data-stream]',li);

			if($(div).attr('data-stream') =='') return;
			$(div).css('background','url(data:'+$(div).attr('data-stream')+')')
		     	.css('background-size','cover');
		});


		$('#parts li:not(:eq(0))').css('transform','scale(0)').removeClass('hidden')

		$('#parts li:not(:eq(0))').each(function(i,li){
			var li = $(li);
			setTimeout(function(){
				li.css('transform','scale(1)');
			},i*200);
		});
		
		

		if(callback!=null) callback();
	});
}

//Ajout ou modification d'élément part
function hackpoint_part_save(element){
	var li = $(element).closest('li');
	
	var data = {
		action : 'hackpoint_part_save',
		resource : $('#sketch-editor').attr('data-id'),
		part : li.attr('data-part'),
		id : li.attr('data-id'),
		label : li.find('.label').val(),
		brand : li.find('.brand input').val(),
		price : li.find('.price input').val(),
		url : li.find('.url').val(),
		picture : li.find('.part-image').attr('data-stream')
	}
	$.action(data,function(r){
		
		li.attr('data-part',r.part);
		li.attr('data-id',r.id)
		$.message('success','Enregistré');
	});
}

function hackpoint_part_find(element){
	var li = $(element).closest('li');
	var label = li.find('.label').val();
	var brand = li.find('.brand input').val();
	var url = "https://www.ebay.fr/sch/i.html?_from=R40&_sacat=0&LH_BIN=1&LH_PrefLoc=2&_sop=15";
	if(null!=brand && brand !='')  label = brand+'+'+label;
	url += "&_nkw="+label;
	window.open(url);
}

function hackpoint_part_add(){

	var tpl = $('#parts li:eq(0)').get(0).outerHTML;

	var data = {
		price : 1,
		url : 'http://ebay.com'
	}
	var item = $(Mustache.render(tpl,data));
	item.removeClass('hidden');
	item.css({
		transform : 'scale(0)',
		opacity : 0,
	});
	$('#parts li:eq(0)').after(item);
	
	item.css({
		transform : 'scale(1) rotate(0deg)',
		opacity : 1,
	});

	init_components(item);

	hackpoint_resource_part_upload(item);





}

function hackpoint_resource_part_upload(item){
	var item = $(item);
	var image = item.find('.part-image');
	image.click(function(e){
		e.preventDefault();
		e.stopPropagation();
		var picker = image.next('input[type="file"]');
		picker.trigger('click');
		picker.change(function(){
			var file = picker.get(0).files[0];
			 var reader  = new FileReader();
			 reader.addEventListener("load", function () {
			
			    image.css('background','url('+reader.result+')')
			    .attr('data-stream',reader.result)
		     	.css('background-size','cover');
			  }, false);
			reader.readAsDataURL(file);
		});
	});
	image.on('drag dragstart dragend dragover dragenter dragleave drop', function (e) {
		   e.preventDefault();
		   e.stopPropagation();
	})
	image.on('drop', function (e) {
		var droppedFiles = e.originalEvent.dataTransfer.files;
		var reader = new FileReader();
		   reader.readAsDataURL(droppedFiles[0]);
		   reader.onload = function () {
		   
		     image.css('background','url('+reader.result+')')
			    .attr('data-stream',reader.result)
		     	.css('background-size','cover');
		   };
		   reader.onerror = function (error) {
		     console.log('Error: ', error);
		   };

	});
		/*
	var preload = $('<div class="preload progress-bar progress-bar-striped progress-bar-animated"></div>');
	item.find('.part-image').append(preload);
	item.find('.part-image').attr('id','part-image-'+$('#parts li').length());
	item.find('.part-image').upload({
		allowed : 'jpg,png,jpeg,bmp,svg',
		size : 0,
		action : 'hackpoint_part_image_upload',
		readonly: false,
		start: function(){
			preload.show();
		},
		success: function(response){
			if(response.previews.length && response.previews[0].name) {
				
			}
			console.log(response);
			preload.fadeOut();
		},
		complete: function(){
			preload.fadeOut();
		}
	});*/
}

//Suppression d'élement part
function hackpoint_resource_part_delete(element){
	if(!confirm('Êtes vous sûr de vouloir supprimer cet item ?')) return;
	var line = $(element).closest('li');

	if(line.attr('data-id')==''){
		line.css('transform','scale(0)');
		setTimeout(function(){
			line.remove()
		},210);
		return;
	}
	$.action({
		action : 'hackpoint_resource_part_delete',
		id : line.attr('data-id')
	},function(r){
		line.css('transform','scale(0)');
		setTimeout(function(){
			line.remove()
		},210);
	});
}

//Suppression d'élement part
function hackpoint_part_delete(element){
	if(!confirm('Êtes vous sûr de vouloir supprimer cet item ?')) return;
	var line = $(element).closest('li');

	if(line.attr('data-id')==''){
		line.css('transform','scale(0)');
		setTimeout(function(){
			line.remove()
		},210);
		return;
	}
	$.action({
		action : 'hackpoint_part_delete',
		id : line.attr('data-id')
	},function(r){
		line.css('transform','scale(0)');
		setTimeout(function(){
			line.remove()
		},210);
	});
}



/** SKETCH **/


//Récuperation d'une liste de sketch dans le tableau #sketchs
function hackpoint_sketch_search(callback){
	
		
	$('#sketchs').fill({
		action:'hackpoint_sketch_search',
		filters : $('#filters').filters(),
		sort : $('#sketchs').sortable_table('get')
	},function(r){

		if(!r.rows) $('.no-sketch').removeClass('hidden');

		init_components('#sketchs');
		$('.progress').click(function(e){
			var x = e.pageX - $(this).offset().left;
       		var percent = Math.round(x *100 / $(this).width());
       		var progressClass = 'bg-danger';

       		if(percent>97) percent = 100;

       	
			if(percent > 30) progressClass  = 'bg-warning';
			if(percent > 45) progressClass  = 'bg-info';
			if(percent > 65) progressClass  = '';
			if(percent > 85) progressClass  = 'bg-success';

			var li = $(this).closest('li');
       		$(this).find('.progress-bar')
       		.css('width',percent+'%')
       		.attr('aria-valuenow',percent)
       		.text(percent+'%')
       		.attr('class','progress-bar '+progressClass);
       		$.action({
				action : 'hackpoint_sketch_progress_save',
				id : li.attr('data-id'),
				progress : percent,
			},function(r){});

       	
		});

		if(callback!=null) callback();
	});
}

//Ajout ou modification d'élément sketch
function hackpoint_sketch_save(){

	if($('.hackpoint').hasClass('readonly')) return;

	$('.sketch-preloader').show();
	var data = {
		action : 'hackpoint_sketch_save',
		id : $('#sketch-form').attr('data-id'),
		label : $('#label').val(),
		state : $('#state').prop('checked'),
		comment : $('#comment').val()
	}
	
	$.action(data,function(){
		$('.sketch-preloader').fadeOut(300);
	});
}

function hackpoint_sketch_download(){
	var id = $('#sketch-form').attr('data-id');

	$.action({
			action : 'hackpoint_sketch_download',
			downloadResponse : true,
			id : id
	},function(r){
		
	});
}

function hackpoint_sketch_share(){

	$('#share-sketch-modal').modalize({
		blur:".hackpoint,#mainMenu",
		height:300
	});
	hackpoint_sketch_share_mode();
	$('.share-input').click(function () {
	   $(this).select();
	});
	$('.share-menu-mode').click(function () {
	   hackpoint_sketch_share_mode();
	});
}

function hackpoint_sketch_share_mode(){
	var tpl = $('.shareCode').html();

	var data = {
		sketch : $('#sketch-form').attr('data-id'),
		resource : $.urlParam('resource'),
		menu : $('.share-menu-mode').prop('checked')?1:0,
		url : window.location.protocol+'//' + window.location.hostname + window.location.pathname
	}
	var html = Mustache.render(tpl,data);
	$('.share-input').html(html);
}


function hackpoint_sketch_save_cover(input,stream){
	console.log('hey');
	var li = input.closest('li');
	$.action({
			action : 'hackpoint_sketch_save_cover',
			stream : stream,
			sketch : li.attr('data-id')
	},function(r){
		input.attr('src',r.stream);
	});
}


//Suppression d'élement sketch
function hackpoint_sketch_delete(element){
	if(!confirm('Êtes vous sûr de vouloir supprimer cet item ?')) return;
	$.action({
		action : 'hackpoint_sketch_delete',
		id : $('#sketch-form').attr('data-id')
	},function(r){
		window.location = 'index.php?module=hackpoint&success=Sketch supprimé';
	});
}



/** RESOURCE **/
	
//Récuperation d'une liste de resource dans le tableau #resources
function hackpoint_resource_search(callback,triggered){
	$('#resources').fill({
		action:'hackpoint_resource_search',
		sketch : $('#sketch-form').attr('data-id'),
		showing : function(li,i){
			//affiche les menu de façon progressive
	    	li.removeClass('hidden')
	    	.css('transform','translateX(-120px)');
	    	
    		setTimeout(function(){
				li
				.css('transform','translateX(0px)');
			},150*i);
		}
	},function(){



		//rend les menu sortables
		$( ".hackpoint.editable #resources" ).sortable({
			axis: "y",
			update: function( event, ui ){
				var sort = [];
				$( "#resources li:visible" ).each(function(i,li){
					li = $(li);
					sort.push(li.attr('data-id'));
				});
				$.action({
					action : 'hackpoint_resource_sort',
					sort : sort
				},function(r){
					
				});
			}
		});
    	$( "#resources" ).disableSelection();
    
    	var trigger =  '#resources li:eq(1)';
    	if(triggered){
    		trigger = triggered;
    	}else if($.urlParam('resource')){
    		trigger = '#resources li[data-id="'+$.urlParam('resource')+'"]';
    	}
		
		$(trigger).trigger('click');

		if(callback!=null) callback();
	});
}

function hackpoint_resource_edit(element){
	var line = $(element).closest('li');
	var id = line.attr('data-id');
	$('#resources li:visible').removeClass('active');
	line.addClass('active');
	$.action({
		action : 'hackpoint_resource_edit',
		id : id
	},function(r){
		$('#sketch-editor')
		.html(r.html)
		.attr('data-id',id)
		.attr('class','resource-'+r.resourceType);
		

		window.history.replaceState(null, null, "index.php?module=hackpoint&page=sheet.sketch&id="+$('#sketch-form').attr('data-id')+"&resource="+id);

		init_components('#sketch-editor');
		if(r.javascript){
			eval(r.javascript);
		}
	});
}

function resource_add_document(files){

	$.action({
		action : 'resource_add_document',
		id: $('#sketch-editor').attr('data-id'),
		files : files
	}, function(r){
		
		$.each(r.files, function(i, file){
			var line = $('#sketch-editor li[data-path="'+file.oldPath+'"]');
			line.attr('data-path', file.relative);
			line.find('a').attr('href', file.url);
			line.find('i.pointer').attr('onclick', 'resource_delete_document(this)');
			if($('.hackpoint').hasClass('readonly')) line.find('i.pointer').hide();
			

			if(!file.icon){
				line.find('img').attr('src', file.url);
			}else{
				line.find('img').after('<i class="'+file.icon+'"></i>');
				line.find('img').remove();
			}
			$('#sketch-editor [data-type="dropzone"] input:not(:visible)').val('');
			
		});

	});
}

function resource_delete_document(element){
	if($('.hackpoint').hasClass('readonly')) return;
	if(!confirm("Êtes-vous sûr de vouloir supprimer ce fichier ?")) return;
	var line = $(element).closest('li');
	$.action({
		action : 'resource_delete_document',
		path : line.attr('data-path')
	},function(r){
		line.remove();
	});
}

function hackpoint_resource_title_edit(event,element){
	event.stopPropagation();
	event.preventDefault();

	var title = $(element);
	var span = $(element).find('span');
	var input = $(element).find('input');
	span.hide();
	input.removeClass('hidden');
	input.focus();
	input.val(span.text());
	input.select();
	
	
	input.blur(function(){
		input.hide();
		span.text(input.val());
		span.show();
		var li = $(this).closest('li');
		$.action({
			action : 'hackpoint_resource_save',
			id : li.attr('data-id'),
			label : input.val()
		},function(r){
			
		});

	});
 	console.log(event,'hey!');
}



function hackpoint_resource_mirrorify(element,data){

	if($('.hackpoint').hasClass('readonly')) data.readOnly = true;
	var editor = CodeMirror.fromTextArea($(element).get(0), data);
	editor.on("blur", function(cm,obj){
		if($('.hackpoint').hasClass('readonly')) return;
		var data = {};
		data.action = 'hackpoint_resource_save_content';
		data.id = $('#sketch-editor').attr('data-id');
		data.content = cm.getValue();
		$('.sketch-preloader').show();
		$.action(data,function(r){
			setTimeout(function(){
				$('.sketch-preloader').fadeOut(200);
			},300);
		});
	});
	editor.on("change", function() { 
		var data ={height:800};
		var wrap = editor.getWrapperElement();      
		var approp = editor.getScrollInfo().height > data.height ? data.height+"px" : "auto";
		if (wrap.style.height != approp) {
			wrap.style.height = approp;
			editor.refresh();
		}
	});
}

//Ajout ou modification d'élément resource
function hackpoint_resource_save(element){
	var data = {
		action:'hackpoint_resource_save',
		sketch:$('#sketch-form').attr('data-id'),
		type:$(element).attr('data-slug')
	}
	$.action(data,function(r){

		var tpl = $('#resources li:eq(0)').get(0).outerHTML;
		var element = $(Mustache.render(tpl,r));
		$('#resources').append(element);

		element.removeClass('hidden')
    	.css('transform','translateX(-120px)');
    	setTimeout(function(){
    		$(element).css('transform','translateX(0px)');
    	},150);

    	element.trigger('click');

	});
}



//Suppression d'élement resource
function hackpoint_resource_delete(element,event){
	event.stopPropagation();
	if(!confirm('Êtes vous sûr de vouloir supprimer cet item ?')) return;
	var line = $(element).closest('li');
	$.action({
		action : 'hackpoint_resource_delete',
		id : line.attr('data-id')
	},function(r){
		
		$('#resources li:visible(:eq(0))').removeClass('active');
		$('#sketch-editor').html('');
		
		
		line.remove();
		
	});
}


function preloader(mode){
	var preloader = $('.hackpoint-preloader');
	if(preloader.length==0){
		preloader = $('<div class="hackpoint-preloader" title="Chargement..."><i class="fas fa-circle-notch fa-spin"></i></div>');
		$('body').append(preloader);
	}
	setTimeout(function(){
		if(mode){
			preloader.addClass('show');
		}else{
			preloader.removeClass('show');
		}
	},50);
}