//handle target
var target = false;
var refreshInterval = null;
var resizeTarget = false;

//CHARGEMENT DE LA PAGE
$(function(){

	if($.urlParam('section') == 'list.widget.share') dashboard_widget_share_search();
	if(($.page()!='' && $.page()!='index') || $.urlParam('module')!=null) return;
	dashboard_dashboardwidget_search();
		
	$('#dashboard-view li').click(function(){
		$('#dashboard-view li').removeAttr('data-selected');
		$(this).attr('data-selected',1);
		dashboard_dashboardwidget_search();
	});
	$('#widget-list').change(function(){
		var option = $('#widget-list option:selected').data();
		option.text = $('#widget-list option:selected').text();

		var description = $('.widgetDescription');
		description.removeClass('hidden');
		$('h3 span', description).text($(this).val() == '' ? 'Sélectionnez un widget' : option.text);
		$('h3 i', description).attr('class',option.icon);
		$('p', description).text(option.description);
		$('.widgetWidth', description).html(option.width=='' ? '' : '<span class="text-muted font-weight-bold mr-2">LARGEUR</span> '+Math.round(option.width*100 /12)+'%');
		$('.widgetColor', description).html(option.background=='' ? '' : '<span class="text-muted font-weight-bold  mr-2">COULEUR</span> <small style="background-color:'+option.background+'"></small><span>'+option.background+'</span>   ');
	});

	if(!$('.dashboard-container').hasClass('readonly')){
		$('#dashboard').sortable({
			distance: 15,
			cancel :'[data-mandatory="1"]',
			tolerance: "pointer",
			handle: ".widget_header",
			opacity: 0.8,
			placeholder: {
				element: function(clone, ui) {
					var classes = clone.attr('class').split(' ');
					for(var key in classes){
						var number = classes[key].match(/col-xl-([0-9])/i);
						if(number != null)
							colSize = number[1] > 9 ? 9 : number[1];
					}
	                return $('<div class="ui_sortable_placeholder widget_placeholder col-xl-'+colSize+' col-md-'+colSize*2+' col-lg-'+colSize*2+'"></div>');
	            },
	            update: function() {
	                return;
	            }
			},
			update:function(event,ui){
				var data = dashboard_dashboardwidget_save_position();
			}
		});
		$( ".widget" ).disableSelection();
	}
});


function init_setting_dashboard(){
	dashboard_dashboard_search();
	dashboard_widget_share_search();
}

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


/** DASHBOARD **/
//Récuperation d'une liste de dashboard dans le tableau #dashboards
function dashboard_dashboard_search(callback){
	$('#dashboards').fill({
		action:'dashboard_dashboard_search'
	},function(){
		if(callback!=null) callback();
	});
}

//Ajout ou modification d'élément dashboard
function dashboard_dashboard_save(){
	var form = $('#dashboard-form');
	var data = form.toJson();

	$.action(data,function(r){
		form.attr('data-id','');
		reset_inputs(form);
		$('#icon').val('far fa-bookmark');
		init_components(form);
		
		$.message('success','Enregistré');
		
		dashboard_dashboard_search();
	});
}

//Récuperation ou edition d'élément dashboard
function dashboard_dashboard_edit(element){
	var line = $(element).closest('tr');

	$.action({
		action:'dashboard_dashboard_edit',
		id:line.attr('data-id')
	},function(r){
		$.setForm('#dashboard-form',r);
		$('#dashboard-form').attr('data-id',r.id);
		init_components('#dashboard-form');
	});
}

//Suppression d'élement dashboard
function dashboard_dashboard_delete(element){
	if(!confirm('Êtes-vous sûr de vouloir supprimer ce dashboard ?')) return;
	var line = $(element).closest('tr');

	$.action({
		action : 'dashboard_dashboard_delete',
		id : line.attr('data-id')
	},function(r){
		line.remove();
		$.message('info','Dashboard supprimé');
	});
}

/** DASHBOARDWIDGET **/
function configure_widget(element){
	var widget = $(element).closest('.widget');
	var configureUrl = widget.attr('data-configure');
	
	if(configureUrl.substring(0,11) == 'setting.php'){
		window.open(configureUrl); 
	}else{
		var modal = $('#configureWidgetModal');
		modal.attr('data-widget',widget.attr('data-id')).modal('show');
		$('.pluginContent', modal).load(widget.attr('data-configure'),{
			id : widget.attr('data-id')
		},function(){
			init_components();
			var callback = widget.attr('data-configure-init');
			if(window[callback]!=null) window[callback](widget,modal);
		});
	}
}

function dashboard_dashboardwidget_save_configuration(){
	var modal = $('#configureWidgetModal');
	var widget = $('.widget[data-id="'+modal.attr('data-widget')+'"]');

	modal.modal('hide');
	
	var callback = widget.attr('data-configure-callback');
	if(window[callback]!=null) window[callback](widget,modal);
}


//Récuperation d'une liste de dashboardwidget dans le tableau #dashboardwidgets
function dashboard_dashboardwidget_search(callback){
	var dashboard = $('#dashboard-view li[data-selected]').attr('data-id');
	if(!dashboard || dashboard=='') return;
	$.action({
		action : 'dashboard_dashboardwidget_search',
		dashboard : dashboard
	},function(r){
		$('#dashboard .widget:visible').remove();

		for(var i in r.rows){
			var widget = r.rows[i];
			dashboard_dashboardwidget_append(widget,function(widget){
				dashboard_dashboardwidget_load(widget);
			});
		}
		clearInterval(refreshInterval);
		refreshInterval = setInterval(function(){
			dashboard_dashboardwidget_refresh();
		},3000);

		if(!$('.dashboard-container').hasClass('readonly')){
			//Gestion du resize de largeur
			$('.widget_resize').draggable({
				axis: "x",
				cancel :'[data-mandatory="1"]',
				start : function(event,ui){
					var widget = ui.helper.closest('.widget');
					$('.widget_content',widget).append('<div class="readonly-veil"></div>');
				},
				drag: function(event,ui) {
					var widget = ui.helper.closest('.widget');
				    var width = widget.attr('data-width');
				    var percent = ui.position.left * 100 / ui.originalPosition.left;
				    var newWidth = Math.round(width * percent/100);
				    newWidth = newWidth<1 ? 1 : newWidth;
				    newWidth = newWidth>12 ? 12 : newWidth;

				    //Gestion taille widget max
				    if(widget.attr('data-maxWidth') && widget.attr('data-maxWidth').length){
				    	maxWidth = widget.attr('data-maxWidth');
					    newWidth = newWidth>maxWidth ? maxWidth : newWidth;
				    }
				    //Gestion taille widget min
			        if(widget.attr('data-minWidth') && widget.attr('data-minWidth').length){
			        	minWidth = widget.attr('data-minWidth');
					    newWidth = newWidth<minWidth ? minWidth : newWidth;
			        }
	
				    widget.removeClass('col-xl-1 col-xl-2 col-xl-3 col-xl-4 col-xl-5 col-xl-6 col-xl-7 col-xl-8 col-xl-9 col-xl-10 col-xl-11 col-xl-12');
				    widget.addClass('col-xl-'+newWidth);

				    widget.removeClass('col-lg-1 col-lg-2 col-lg-3 col-lg-4 col-lg-5 col-lg-6 col-lg-7 col-lg-8 col-lg-9 col-lg-10 col-lg-11 col-lg-12');
				    widget.addClass('col-lg-'+newWidth*2);

				    widget.removeClass('col-md-1 col-md-2 col-md-3 col-md-4 col-md-5 col-md-6 col-md-7 col-md-8 col-md-9 col-md-10 col-md-11 col-md-12');
				    widget.addClass('col-md-'+newWidth*2);
	
				},
				stop: function(event,ui){
					var resizebar = ui.helper;
					var widget = resizebar.closest('.widget');
					$('.widget .readonly-veil').remove();
					var width = widget.attr('data-width');
					var newWidth = widget.attr('class').match(/col-xl-([0-9]*)/)
					newWidth = newWidth[1];
					
					if(newWidth!=width){
					    $.action({
							action : 'dashboard_dashboardwidget_resize',
							widget : widget.attr('data-id'),
							width: newWidth
						},function(r){
							widget.attr('data-width',newWidth);
							
						});
					}
					resizebar.removeAttr('style');
				}
			});
		}
	});
}

function dashboard_dashboardwidget_refresh(){
	$.action({
		action : 'dashboard_dashboardwidget_refresh',
		dashboard : $('#dashboard-view li[data-selected]').attr('data-id')
	},function(r){

		for(var id in r.rows){
			var widget = r.rows[id];

			if(widget.widget){
				var header = $('.widget[data-id="'+id+'"]').find('.widget_header'); 
				if(widget.widget.title) header.find('span').text(widget.widget.title);
				if(widget.widget.icon) header.find('i').attr('class','fa '+widget.widget.icon);
				if(widget.widget.background) header.css('backgroundColor',widget.widget.background);
			}

			if(widget.callback){
				if(window[widget.callback]!=null) window[widget.callback]($('.widget[data-id="'+id+'"]'),widget.data);
			}
			
		}
	});
}

//Mise à jour des infos d'un élement widget à partir d'un object data
function dashboard_dashboardwidget_render(widget,data){
	widget.attr('data-id',data.id);
	widget.removeClass (function (index, css) {
		return (css.match (/(^|\s)col-xl-\S+/g) || []).join(' ');
	});
	var width = data.width!=0 ? data.width : data.defaultWidth; 

	widget.attr('data-id',data.id)
		.attr('data-load',data.load)
		.attr('data-configure',data.configure)
		.attr('data-configure-callback',data.configure_callback)
		.attr('data-configure-init',data.configure_init)
		.attr('data-delete',data.delete)
		.attr('data-mandatory',data.mandatory && data.mandatory==1 ?1:0)
		.attr('data-model',data.model)
		.attr('data-width',width)
		.addClass('col-xl-'+width)
		.addClass('col-lg-'+width*2)
		.addClass('col-md-'+width*2)
		.find('.widget_header')
		.css('background',data.background)
		.find('i:eq(0)').attr('class',data.icon);

	if(data.minWidth && data.minWidth!=0) widget.attr('data-minWidth', data.minWidth);
	if(data.maxWidth && data.maxWidth!=0) widget.attr('data-maxWidth', data.maxWidth);

	widget.find('.widget_header span:eq(0)').html(data.title);
	widget.find('.widget_content').html(data.content);
		
	var options = '';
	for(var k in data.options){
		var option = data.options[k];
		options+='<li onclick="'+option.function+'" '+(option.title ? 'title="'+option.title+'"':'')+'><i class="fa '+option.icon+'"></i> '+(option.label ? option.label:'')+'</li>';
	}
	if(data.configure) options+="<li title='Configurer' onclick='configure_widget(this);'><i class='fa fa-wrench'></i></li>";
	options+="<li title='Supprimer' onclick='dashboard_dashboardwidget_delete(this);'><i class='fa fa-times'></i></li>";

	widget.find('.widget_options').html(options);
	widget.data('data',data);
	widget.removeClass('hidden');

	return widget;
}

//Modification d'un widget existant
function dashboard_dashboardwidget_update(data){
	var widget = $('.widget[data-id="'+data.id+'"]');
	var data = $.extend(widget.data('data'), data);
	dashboard_dashboardwidget_render(widget,data);
}

//Ajout ou modification d'élément dashboardwidget
function dashboard_dashboardwidget_save(){
	var data = $('#dashboardwidget-form').toJson();
	$.action(data,function(r){
		$('#dashboardwidget-form').attr('data-id','');
		dashboard_dashboardwidget_search();
		$.message('success','Enregistré');
	});
}

//Chargement du contenu php du widget
function dashboard_dashboardwidget_load(widget){
	
	$.getJSON(widget.load,{
		id : widget.id,
		model : widget.model,
		content:'',
	},function(r){
		if(r.error && r.error.code == 403){
			$('.widget[data-id="'+widget.id+'"]').remove();
			return;
		}
		dashboard_dashboardwidget_update(r);
		var data = $.extend($('.widget[data-id="'+widget.id+'"]').data('data'), r.widget);

		var init = 'widget_'+data.model.replace(/[^a-z0-9]/i,'_')+'_init';
		if(window[init]!=null) window[init]();
	});
}

//Ajout (manuel par l'user) d'un widget
function dashboard_dashboardwidget_add(){
	$.action({
		action : 'dashboard_dashboardwidget_add',
		dashboard : $('#dashboard-view li[data-selected]').attr('data-id'),
		widget : $('#widget-list').val()
	},function(r){
		if(r.message) $.message('info',r.message);
		$('#dashboard_dashboardwidget_appendModal').modal('hide');
		dashboard_dashboardwidget_search();
	});
}

//Ajout (depuis le code) d'un widget
function dashboard_dashboardwidget_append(data,callback){
	var tpl = $('#dashboard .widget:hidden').get(0).outerHTML;
	var widget = $(tpl);
	$('#dashboard').append(widget);
	if(data.css!=null){
		for(k in data.css){
			var css = data.css[k];
			if($('link[href="'+css+'"]').length!=0) continue;

			//on supprime tout autre css ayant la même base mais des versions plus vielles
			var baseCss = css.replace(/\?v=.*/gm,'');
			$('link[href^="'+baseCss+'"]').remove();

			var cssFile = document.createElement('link');
			cssFile.setAttribute("rel","stylesheet");
			cssFile.setAttribute("type","text/css");
			cssFile.setAttribute("href", css);
			document.getElementsByTagName("body")[0].appendChild(cssFile);
		}
	}
	dashboard_dashboardwidget_render(widget,data);
	if(data.js!=null){
		dashboard_load_js(data.js,0,function(){
			if(callback) callback(data);
		});
	}else{
		if(callback) callback(data);
	}
	
	
}

function dashboard_load_js(files,iteration,callback){
	var js = files[iteration];

	if($('script[src="'+js+'"]').length!=0 || js==null) {
		if(files.length > iteration) dashboard_load_js(files,iteration+1,callback);
		if((files.length-1) == iteration) if(callback) callback();
		return;
	}
	//on supprime tout autre js ayant la même base mais des versions plus vielles
	var baseJs = js.replace(/\?v=.*/gm,'');
	$('script[src^="'+baseJs+'?"]').remove();

	var jsFile = document.createElement('script');
	jsFile.setAttribute("type","text/javascript");
	document.getElementsByTagName("body")[0].appendChild(jsFile);
	jsFile.onload = function() {
		if(files.length > iteration) dashboard_load_js(files,iteration+1,callback);
		if((files.length-1) == iteration) if(callback) callback();
	};
	jsFile.src =  js;
}

//Récuperation ou edition d'élément dashboardwidget
function dashboard_dashboardwidget_edit(widget){
	var line = $(element).closest('tr');
	$.action({action:'dashboard_dashboardwidget_edit',id:line.attr('data-id')},function(r){
		$.setForm('#dashboardwidget-form',r);
		$('#dashboardwidget-form').attr('data-id',r.id);
	});
}

//Suppression d'élement dashboardwidget
function dashboard_dashboardwidget_delete(element){
	var element = $(element).closest('.widget');
	var data = element.data('data');
	
	$.action({
		action : 'dashboard_dashboardwidget_delete',
		dashboard : $('#dashboard-view li[data-selected]').attr('data-id'),
		widget : data.id,
	},function(r){
		element.remove();
		if(r.message) $.message('info',r.message);
		else $.message('info', 'Widget supprimé');
		if(data.delete != null){
			$.getJSON(data.delete,$.extend(data,{content:''}));
		}
	});
}



//Enregistrement de toutes les positions de widget
function dashboard_dashboardwidget_save_position(){
	var positions = [];
	$('.widget:visible').each(function(i,element){
		positions.push({id:$(element).attr('data-id'),position:$(element).index()});
	});
	
	$.action({
		action : 'dashboard_dashboardwidget_save_position',
		dashboard : $('#dashboard-view li[data-selected]').attr('data-id'),
		positions : positions,
	},function(r){
		
	});

}


/** DASHBOARDWIDGETSHARE **/
//Récuperation d'une liste de dashboardwidgetshare dans le tableau #dashboardwidgetshares
function dashboard_widget_share_search(callback){
	$('#dashboard-widget-shares').fill({
		action: 'dashboard_widget_share_search'
	},function(response){
		if(callback!=null) callback();
	});
}

//Ajout ou modification d'élément dashboardwidgetshare
function dashboard_widget_share_save(){
	var data = $('#dashboard-widget-share-form').toJson();
	var target = $('#uid').data('values');

	if(target){
		data.entity = target[0].entity;
		data.uid = target[0].uid;
	}

	$.action(data,function(r){
		$('#dashboard-widget-share-form').attr('data-id','');
		$('#dashboard-widget-share-form').clear();
		dashboard_widget_share_search();
		
		$.message('success','Enregistré');
	});
}


//Récuperation ou edition d'élément dashboardwidgetshare
function dashboard_widget_share_edit(element){
	var line = $(element).closest('tr');

	$.action({
		action: 'dashboard_widget_share_edit',
		id: line.attr('data-id')
	},function(r){
		$.setForm('#dashboard-widget-share-form',r);
		init_components('#dashboard-widget-share-form');
		$('#dashboard-widget-share-form').attr('data-id',r.id);
	});
}

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