var reading = false;

//CHARGEMENT DE LA PAGE
function init_plugin_notification(){
	switch($.urlParam('page')){
		default:

		break;
	}

	$('#notifications').fill({
		action : 'notification_user_notification_search',
		unread : false,
	}, function(r){
		count_notifications();
		if(!r.rows) $('#notifications').append('<div class="text-center no-notification">Aucune notification</div>');
	});

	$('.categoryCheckbox').on('click', function(){
		$(this).closest('li.category').find('li.item input.itemCheckbox').prop('checked', $(this).prop('checked'));
		notification_filters();
	});

	$('.itemCheckbox').on('click', function(){
		notification_filters();
	});

	$('.itemLabel').on('click', function(){
		var itemCheckbox = $(this).closest('li.item').find('input.itemCheckbox');
		itemCheckbox.prop('checked', !itemCheckbox.prop('checked'));
		notification_filters();
	});
	$('.categoryIcon:eq(0)').trigger('click');
}

function init_setting_notification(){
	$('#notifications-pinned').sortable_table({
		onSort : notification_search
	});
}

$(document).ready(function(e){
	notification_user_notification_search();

	//Gestion animation cloche sans bug
	$('#dropdownNotification > i').bind("webkitAnimationEnd mozAnimationEnd animationEnd", function(){
		$('#dropdownNotification').removeClass("animated");
	});
	$('#dropdownNotification').mouseenter(function(){
		$(this).addClass("animated");
	});
});

// fonctions de filtres
function notification_filters(){
	var filters = $('.categories').find('input[type=checkbox]:checked');
	if(filters.length > 0){
		$('li.notification-item').addClass('hidden');
		filters.each(function(){
			filterItem = $(this).attr('data-item');
			$('li.notification-item').each(function(){
				if($(this).attr('data-item') == filterItem) $(this).removeClass('hidden');
			});
		});
	}else{
		$('li.notification-item:not(:eq(0))').removeClass('hidden');
	}
	count_notifications();
}

function count_notifications(){
	var notifTotal = 0;
	$('.itemBadge').text(0);

	$('.notification-item.unread').each(function(){
		var notifItem = $(this).attr('data-item');
		var nbNotifItem = parseInt($('.itemBadge[data-item='+notifItem+']').text());
		$('.itemBadge[data-item='+notifItem+']').text(nbNotifItem+1);
	});

	$('.notifications-list .categories .category').each(function(){
		var category = $(this);
		var notifCat = 0;
		category.find('.item[data-category='+category.attr('data-category')+'] span.itemBadge').each(function(){
			notifCat += parseInt($(this).text());
		});

		category.find('.boxTitle span.categoryBadge').text(notifCat);
		notifTotal += parseInt(notifCat);
	});

	/* couleur sur badge */
	$('.notifications-list .category .badge').each(function(){
		var badge = $(this);
		(parseInt(badge.text()) > 0) ? badge.removeClass('badge-light').addClass('badge-primary') : badge.removeClass('badge-primary').addClass('badge-light');
	});

	$('#notifCounterFilter').text(parseInt(notifTotal));
	if(parseInt(notifTotal) > 0){
		$('#notifCounterFilter').removeClass('badge-light').addClass('badge-primary');
		$('#notifWord').text('notifications');
	}else{
		$('#notifCounterFilter').removeClass('badge-primary').addClass('badge-light');
		$('#notifWord').text('notification');
	}

	$('.notification-number').text(parseInt(notifTotal));
	if(parseInt(notifTotal) <= 0) $('.notification-number').addClass('hidden');
	if(parseInt(notifTotal) > 5) $('.notification-number').text('5+');

	(notifTotal > 0) ? $('#readState').removeClass('hidden') : $('#readState').addClass('hidden');

	if(parseInt($('.notification_menu .dropdown-menu').find('.notification-item[data-id]').length) <= 0){
		$('.notification_menu .dropdown-menu').html('<a class="no-notif dropdown-item notification" href="index.php?module=notification">Aucune notification pour le moment</a>');
	}else{
		$('.notification_menu .dropdown-menu .no-notif').addClass('hidden');
	}

	if(parseInt($('#notifications').find('.notification-item[data-id]').length) <= 0){
		$('#notifications').append('<div class="no-notif text-center no-notification">Aucune notification pour le moment</div>');
	}else{
		$('#notifications .no-notif').addClass('hidden');
	}

	if($('.notification-item').length > 2){
		$('#deleteState').removeClass('hidden');
	}else{
		$('#deleteState').addClass('hidden');
	}
}

//Marquer comme lu/non lu une notification
function notification_user_notification_toggle_read(element,event,container){
	if(event) event.stopPropagation();
	if(!container) container = 'li';
	var line = $(element).closest(container);
	var notifId = line.attr('data-id');
	$.action({
		action : 'notification_usernotification_toggle_read',
		id : notifId
	},function(r){
		var notifCounter = $('.notification-number');
		var number = $('.notification_menu .notification-number');
		var oldNumber = parseInt(number.text());
		var notif = 0;
		var totalNotif = 0;

		$('.badge-category[data-category]').each(function(){
			var notifCat = 0;
			$('span.badge-item[data-category="'+$(this).attr('data-category')+'"]').each(function(){
				if(r.unread[$(this).attr('data-item')] != null){
					$(this).removeClass('badge-light').addClass('badge-primary');
					notif = r.unread[$(this).attr('data-item')];
				}else{ // nbNotif = 0
					notif = 0;
					$(this).removeClass('badge-primary').addClass('badge-light');
				}
				$(this).text(notif);
				notifCat += parseInt(notif);
			});

			$(this).text(notifCat);
			if(notifCat!=0){
				if($(this).hasClass('badge-light')) $(this).removeClass('badge-light').addClass('badge-primary');
			}else{
				if($(this).hasClass('badge-primary')) $(this).removeClass('badge-primary').addClass('badge-light');
			}
			totalNotif += parseInt(notifCat);
		});

		if(totalNotif!=0){
			notifCounter.removeClass('hidden').html(totalNotif);
			if($('#totalNotif').hasClass('badge-light')) $('#totalNotif').removeClass('badge-light').addClass('badge-primary');
		}else{
			if($('#totalNotif').hasClass('badge-primary')) $('#totalNotif').removeClass('badge-primary').addClass('badge-light');
		}
		$('#totalNotif').html(totalNotif);
		$('#notifWord').text("notification"+((totalNotif>1) ? "s": ""));

		totalNotif.toString().indexOf('+') !== -1 ? notifCounter.addClass('more-unreads') : notifCounter.removeClass('more-unreads');

		if(!$.isNumeric(oldNumber)) oldNumber = 0;

		var notificationItem = $('.notification-item[data-id='+notifId+']');
		if(r.read){
			notificationItem.each(function(){
				if($(this).hasClass('unread')){
					$(this).removeClass('unread').addClass('read');
				}else if($(this).hasClass('notification-unread')){
					$(this).removeClass('notification-unread').addClass('notification-read');
				}
			});

			$(element).attr('title', 'Marquer comme non lu');
			if(oldNumber==1) number.removeAttr('style');
		} else {
			notificationItem.each(function(){
				if($(this).hasClass('read')){
					$(this).removeClass('read').addClass('unread');
				}else if($(this).hasClass('notification-read')){
					$(this).removeClass('notification-read').addClass('notification-unread');
				}
			});

			$(element).attr('title', 'Marquer comme lu');
			if(oldNumber==0) number.removeClass('hidden');
		}

		count_notifications();
	});
}
function notification_user_notification_read_all(element){
	event.preventDefault();
	event.stopPropagation();

	var container = $('.'+element);
	var ids = [];

	container.find('.notification-item').each(function(){
		if($.isNumeric($(this).data('id'))) ids.push($(this).data('id'));
	});

	$.action({
		action : 'notification_user_notification_read_all',
		id : JSON.stringify(ids)
	},function(r){
		$.each(r.read, function(index, value){
			if(typeof($('.notification-item[data-id='+index+']')) != 'undefined'){
				var notificationItem = $('.notification-item[data-id='+index+']');
				notificationItem.each(function(){
					if($(this).hasClass('unread')){
						$(this).removeClass('unread').addClass('read');
					}else if($(this).hasClass('notification-unread')){
						$(this).removeClass('notification-unread').addClass('notification-read');
					}
				});
			}
		});
		count_notifications();
	});
}

//Récupération des notifications
function notification_user_notification_search(){
	var menu = $('.notification_menu .dropdown-menu');
	menu.html('<div class="w-100 text-center p-2"><i class="fas fa-spinner fa-pulse"></i> Chargement</div>');

	$.action({
		action : 'notification_user_notification_search',
		excerpt : true,
		unread: true
	},function(r){
		if(typeof r == "undefined" || ($.isArray(r) && !r.length)) return;
		if(typeof r.unread == "undefined"){
			$.message('error','Un problème a provoqué une erreur fatale',0);
			return;
		}

		var notifCounter = $('.notification-number');
		var notifCounterFilter = $('#notifCounterFilter');

		if(r.unread!='0') notifCounter.removeClass('hidden').html(r.unread);
		if(r.unread.toString().indexOf('+') !== -1) notifCounter.addClass('more-unreads');

		menu.html('<a class="dropdown-item notification" href="index.php?module=notification">Aucune notification</a>');
		if(r.rows && r.rows.length>0) menu.html('');
		for (var key in r.rows) {
			var notification = r.rows[key];
			var notificationLine = $(Mustache.render($('.notification-template').html(),notification));
			menu.append(notificationLine);
		}
		$('.notification_menu .dropdown-menu .dropdown-divider').last().remove();
		menu.append('<div class="dropdown-divider"></div><a class="dropdown-item see-all-link" href="index.php?module=notification">Voir toutes les notifications</a>')
		menu.prepend('</div><div class="dropdown-item all-as-read" onclick="notification_user_notification_read_all(\'dropdown-menu\', event);">Tout marquer comme lu</div><div class="dropdown-divider">')
	});

	count_notifications();
}

//Suppression d'élement user notification
function notification_user_notification_delete(element,event,container){
	if(event) event.stopPropagation();
	if(!container) container = 'li';
	if(!confirm('Êtes-vous sûr de vouloir supprimer cet item ?')) return;
	var line = $(element).closest(container);
	var notifId = line.attr('data-id');

	$.action({
		action : 'notification_usernotification_delete',
		id : notifId
	},function(r){
		//Suppression ligne notif
		$('.notification-item[data-id='+notifId+']').remove();

		count_notifications();

		$.message('info','Notification supprimée');
	});
}

function notification_user_notification_delete_all(element){
	if(!confirm("Êtes-vous sûr de vouloir supprimer toutes les notifications ?")) return;

	event.preventDefault();
	event.stopPropagation();

	var container = $('.'+element);
	var ids = [];

	container.find('.notification-item').each(function(){
		if($.isNumeric($(this).data('id'))) ids.push($(this).data('id'));
	});

	$.action({
		action : 'notification_usernotifications_delete',
		id : JSON.stringify(ids)
	},function(r){
		$.each($('.notification-item[data-id]'), function(){
			$(this).remove();
		});

		count_notifications();
	});
}


//Sauvegarde préférences notification
function notification_user_save_preference(){
	var data = $('#notification_preference').toJson();
	data.action = 'notification_user_save_preference';
	data.preferences = {};
	$('#notification_categories .category').each(function(i,elementParent){
		var category = $(elementParent).attr('data-slug');
		var methods = {};
		$(elementParent).find('input[type="checkbox"]').each(function(i, input){
			var dataMethod = $(input).attr('data-method');
			var isChecked = $(input).prop('checked');
			methods[category+'_'+dataMethod] = isChecked;
		});
		data.preferences[category] = methods;
	});

	$.action(data,function(r){
		$.message('success','Préférences sauvegardées');
	});
}



/** NOTIFICATION **/

//Récuperation d'une liste de notification dans le tableau #notifications
function notification_search(callback){
	var box = new FilterBox('#filters');
	$('#notifications-pinned').fill({
		action:'notification_search',
		filters : box.filters(),
		sort : $('#notifications-pinned').sortable_table('get'),
		showing : function(item,i){
			item.css({
				transform:'translateX(-150px)',
				transition:'all 0.15s ease-in-out',
				opacity : 0
			}).removeClass('hidden');
			setTimeout(function(){
				item.css({
					transform:'translateX(0px)',
					opacity : 1
				})
			},(i+1)*10);
		}
	},function(response){
		$('.results-count span').text(response.pagination.total);
		if(callback!=null) callback();
	});
}



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

//Envois manuel d'une notification
function notification_send(){
	if(isProcessing) return;
	var form = $('#notification-send');
	var data = form.toJson();
	$('.btn-send').addClass('btn-preloader');

	isProcessing = true;
	$.action(data,function(r){
		$.message('success','Notification envoyée');
		reset_inputs(form);
		$('.btn-send').removeClass('btn-preloader');
		$('.data-type-dropdown-select .dropdown-menu a[data-value="notice"]',form).click();
		init_components('.user-picker');
		isProcessing = false;
	}, function(){
		isProcessing = false;
	});
}



function notification_setting_save(){
	$.action({
		action : 'notification_setting_save',
		fields : $('#notification-setting-form').toJson(),
		followings : $('#notification-default-following').toJson()
	},function(){
		$.message('success','Enregistré');
	});
}