
$(function(){
	notification_user_notification_search();
});

//CHARGEMENT DE LA PAGE
function init_plugin_notification(){
	switch($.urlParam('page')){
		default:
			$('#notifications').fill({
				action : 'notification_user_notification_search'
			}, function(r){
				if(!r.rows)
					$('#notifications').append('<div class="text-center no-notification">Aucune notification</div>');
			});
		break;
	}
}

$(document).ready(function(e){
	//Positionnement icône des notifications
	if($(document).width() <= 767){
		var notifIcon = $('#loginHeader > .notification_menu').detach();
		$('#mainMenu > button.navbar-toggler').before(notifIcon);
	}

	//Meilleure ergonomie pour choisir les catégories de notification
	$('#notification_categories').on('click', ' .list-group-item.list-group-item-action', function(e){
		var checkbox = $(this).find('label.check-component>input[type="checkbox"]');

		checkbox.prop('checked', !checkbox.prop("checked"));
		checkbox.attr('checked', !checkbox.prop("checked"));
	});
});

//Changement positionnement icône des 
//notifs au redimensionnement de la fenêtre
$(window).resize(function(event) {
	if($(document).width() > 767){
		var notifIcon = $('#mainMenu > .notification_menu').detach();
		$('#loginHeader').prepend(notifIcon);
	}
	if($(document).width() <= 767){
		var notifIcon = $('#loginHeader > .notification_menu').detach();
		$('#mainMenu > button.navbar-toggler').before(notifIcon);
	}
});

//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 number = $('.notification_menu .notification-number');
	var notifId = line.attr('data-id');
	$.action({
		action : 'notification_usernotification_toggle_read',
		id : notifId
	},function(r){
		var oldNumber = parseInt(number.text());
		if(!$.isNumeric(oldNumber)) oldNumber = 0;
		if(r.read){
			$('.notification-item[data-id='+notifId+']').removeClass('unread').removeClass('notification-unread');
			$(element).attr('title', 'Marquer comme non lu');
			if(oldNumber==1) number.removeAttr('style');
			number.text(oldNumber-1)
		} else {
			$('.notification-item[data-id='+notifId+']').addClass('unread').addClass('notification-unread');
			$(element).attr('title', 'Marquer comme lu');
			if(oldNumber==0) number.show();
			number.text(oldNumber+1);
		}
	});
}

function notification_user_notification_all_read(element, event){
	event.preventDefault();
	event.stopPropagation();
	var notifDropdown = $(element).closest('.dropdown-menu');
	var notifs = $('.dropdown-item.notification-unread', notifDropdown);
	if(!notifs.length) return;
	
	//Choix entre uniquement les notifs non lues affichées
	$.each(notifs, function(index, value){
		notification_user_notification_toggle_read(value, event, '.dropdown-item');
	});
	//Ou prendre toutes les notifs non lues
	// $.action({
	// 	action: 'notification_usernotification_all_read'
	// }, function(r){
		
	// });
}

//Récupération des notifications
function notification_user_notification_search(){
	var menu = $('.notification_menu .dropdown-menu');
	menu.html('Chargement...');
	$.action({
		action : 'notification_user_notification_search',
		synthesis : true,
	},function(r){
		if(r.unread!='0') $('.notification-number').show().html(r.unread);
		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_all_read(this, event);">Tout marquer comme lu</div><div class="dropdown-divider">')
	});
}

//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){
		var menu = $('.notification_menu .dropdown-menu');
		line.remove();

		//Suppression ligne notif dans le dropdown
		$('.notification-item[data-id='+notifId+']').remove();
		$('.dropdown-divider[data-notification='+notifId+']', menu).remove();

		//Gestion affichage de la dernière notif supprimée
		if(!$('.dropdown-item[data-id]', menu).length){
			menu.html('<a class="dropdown-item notification" href="index.php?module=notification">Aucune notification pour le moment</a>');
			$('#notifications').append('<div class="text-center no-notification">Aucune notification pour le moment</div>');
		}

		//Gestion affichage dynamique nombre de notification
		var notifNbContainer = $('.notification-number');
		var notifNb = parseInt(notifNbContainer.text())
		notifNb-1 < 1 ?	notifNbContainer.text(0).removeAttr('style') : notifNbContainer.text(notifNb-1);

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


//Sauvegarde préférences notification
function notification_user_save_preference(){
	var data = $('#notification_preference').toJson();
	data.action = 'notification_user_save_preference';
	data.categories = [];
	$('#notification_categories .category').each(function(i,element){
		element = $(element);
	
		if(element.find('input[type="checkbox"]:checked').length!=0)
			data.categories.push(element.attr('data-slug')); 
	});

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

// /* Notification via browser */
// //Request permission on page load
// document.addEventListener('DOMContentLoaded', function () {
// 	if (!Notification) return;
// 	if (Notification.permission !== "granted") Notification.requestPermission();
// });

// //Émet une notification en dehors du navigateur
// function emit_notification(infos) {
// 	var url = window.location.href;
// 	var filename = url.substring(url.lastIndexOf('/')+1);
// 	var href = url.replace(filename,'');

// 	if(Notification.permission !== "granted") {
// 		Notification.requestPermission();
// 	} else {
// 		infos.icon = infos.icon ? infos.icon : href+'img/logo/logo.png';
// 		infos.title = infos.title ? infos.title : 'Nouvelle notification';
// 		infos.body = infos.body ? infos.body : 'Vous avez reçu une nouvelle notification en provenance de '+href;

// 		var notification = new Notification(
// 			infos.title, {
// 				icon: infos.icon,
// 				body: infos.body,
// 			}
// 		);
// 		infos.link = infos.link ? infos.link : href+'index.php?module=notification';
// 		notification.onclick = function() {
// 			window.open(infos.link);
// 		};

// 	}
// }

//Notifications avancée avec utilisation d'un Service Worker
// navigator.serviceWorker.register('sw.js');
// function showNotification() {
// 	Notification.requestPermission(function(result) {
// 		if (result === 'granted') {
// 			navigator.serviceWorker.ready.then(function(registration) {
// 				registration.showNotification('Vibration Sample', {
// 					body: 'Buzz! Buzz!',
// 					icon: '../images/touch/chrome-touch-icon-192x192.png',
// 					vibrate: [200, 100, 200, 100, 200, 100, 200],
// 					tag: 'vibration-sample'
// 				});
// 			});
// 		}
// 	});
// }