import '../bootstrap';

// any CSS you require will output into a single css file (admin.css in this case)
require('../css/admin.css');
require('bootstrap');
require('../css/common.css');

require('../js/geoloc.js');
require('../js/flash-messages.js');
const $ = require("jquery");

$('#flash-messages').flashNotification('init');

$(document).ready(function() {

	loadDynamicChart();
	function loadDynamicChart() {
		$('.loadDynamicChart').each(function() {
		    var self = $(this);
		    $.ajax({
		        url : self.data('url'),
		        type: 'get',
		        success: function(data) {
		            if(data.success == true && data.html != null) {
	                    self.parent().html(data.html);
	                    self.addClass('label-success');
		            } else {
		                self.addClass('label-error');
		            }
		        },
		        error: function(data) {
		        	self.addClass('label-error');
		        }
		    });
		});

	}
	/*
	 * On user edit page, on the rolesgroup checkbox:
	 *		- display 'group' select if "Gestionnaire de groupe" is checked
	 *		- display 'comptoir' select if "Comptoir" is checked
	*/
	function possiblegroups_display_selects(e) {
		var label = $(this).closest('li').find('.control-label__text')[0].textContent.trim().toLowerCase()
		var isChecked = $(this).closest('li').find('.checked').length > 0

		if (label.includes('comptoir')) {
			if (isChecked) {
				$('.comptoirsgeres_select').removeClass('hide')
			} else {
				$('.comptoirsgeres_select').addClass('hide')
			}
		} else if (label.includes('groupe')) {
			if (isChecked) {
				$('.groupesgeres_select').removeClass('hide')
			} else {
				$('.groupesgeres_select').addClass('hide')
			}
		} else if (label.includes('contact')) {
			if (isChecked) {
				$('.groupecontactsgeres_select').removeClass('hide')
			} else {
				$('.groupecontactsgeres_select').addClass('hide')
			}
		} else if (label.includes('trésorier')) {
			if (isChecked) {
				$('.groupetresoriersgeres_select').removeClass('hide')
			} else {
				$('.groupetresoriersgeres_select').addClass('hide')
			}
		}
	}

	$('.possible_group_cblist li .checkbox label').on('click', possiblegroups_display_selects);
	$('.possible_group_cblist li .checkbox label ins').on('click', possiblegroups_display_selects);


	$('.graphStatsButton').on('click', function (e) {
		e.preventDefault();
		var self = $(this);
		$.ajax({
			url : self.data('url'),
			type: 'get',
			success: function(data) {
				if(data.success == true && data.html != null) {
					$(self.data('target')).html(data.html);
					loadDynamicChart()
				} else {
					self.addClass('label-error');
				}
			},
			error: function(data) {
				self.addClass('label-error');
			}
		});
	});


	$('.editableboolean').on('click', function (e) {
	    e.preventDefault();
	    var self = $(this);
	    $.ajax({
	        url : self.data('url'),
	        type: 'post',
	        data : {'value' : (self.data('value') == 'true')},
	        success: function(data) {
	            if(data.status == 'success' && !data.messages) {
	                if (data.newvalue == 'false') {
	                    self.text('non');
	                    self.data('value', 'false');
	                    self.addClass('label-danger');
	                    self.removeClass('label-success');
	                } else {
	                    self.data('value', 'true');
	                    self.text('oui');
	                    self.removeClass('label-danger');
	                    self.addClass('label-success');
	                }
	            } else {
	                // $(this).addClass('error');
	            }
	        }
	    });
	});

	// Hide or display Cotisation, Profils de Cotisation and Products Families submenu depending on TAV env
	const tav_env = document.getElementsByName('is-tav-env')[0].getAttribute('content');

	let linksToCotisationAdherent = $('a[href="/admin/cotisation_adherent/list"]');
	for(let i = 0 ; i < linksToCotisationAdherent.length ; i++) {
		if(linksToCotisationAdherent[i].innerText === "Cotisation") {
			linksToCotisationAdherent[i].parentNode.style.display = (tav_env === "1") ? "none" : "";
		}
	}
	let linksToCotisationPresta = $('a[href="/admin/cotisation_prestataire/list"]');
	for(let i = 0 ; i < linksToCotisationPresta.length ; i++) {
		if(linksToCotisationPresta[i].innerText === "Cotisation") {
			linksToCotisationPresta[i].parentNode.style.display = (tav_env === "1") ? "none" : "";
		}
	}
	let linksToProfilDeCotisation = $('a[href="/admin/profilcotisation/list"]');
	for(let i = 0 ; i < linksToProfilDeCotisation.length ; i++) {
		if(linksToProfilDeCotisation[i].innerText === "Profils De Cotisation") {
			linksToProfilDeCotisation[i].parentNode.style.display = (tav_env === "1") ? "" : "none";
		}
	}
	let linksToProductsFamily = $('a[href="/admin/app/productfamily/list"]');
	for(let i = 0 ; i < linksToProductsFamily.length ; i++) {
		if(linksToProductsFamily[i].innerText === "Familles de produits") {
			linksToProductsFamily[i].parentNode.style.display = (tav_env === "1") ? "" : "none";
		}
	}


	var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;

	var moyenDePaiement = document.querySelector('[id$="_moyenDePaiement"].select2-container a span');
	if(moyenDePaiement) {
		var moyenDePaiementObserver = new MutationObserver(actionOnMoyenDePaiementChange);
		moyenDePaiementObserver.observe(moyenDePaiement, {
			childList: true
		});
		function actionOnMoyenDePaiementChange() {
			var selector = document.querySelector('[id$="_jourPrelevement"].form-group');
			if (selector !== null) {
				selector.style.display = moyenDePaiement.innerHTML === "prélèvement" ? "" : "none";
			}
		}
		actionOnMoyenDePaiementChange();
	}

	var recevoirUnRappel = document.querySelector('[id$="_mailRappelCotisation"].form-group div div label div');
	if(recevoirUnRappel) {
		var recevoirUnRappelObserver = new MutationObserver(actionOnRecevoirUnRappelChange);
		recevoirUnRappelObserver.observe(recevoirUnRappel, {
			attributes: true
		});
		function actionOnRecevoirUnRappelChange() {
			var selector = document.querySelector('[id$="_jourMailRappelCotisation"].form-group');
			if (selector !== null) {
				selector.style.display = recevoirUnRappel.classList.contains('checked') ? "" : "none";
			}
		}
		actionOnRecevoirUnRappelChange();
	}

	if($(".fixBalanceAdherentFormPart").length > 0) {
		if (!$(".fixBalanceAdherentFormPart").parent().parent().hasClass('has-error')) {
			$(".fixBalanceAdherentFormPart").parent().parent().hide();
		}
		$(".fixBalanceAdherentFormPart").first().parent().parent().before(
			"<div class='form-group'><input class='btn btn-primary' type='button' id='showFieldsToFixBalance' value='Afficher les champs pour corriger le solde'></input></div>"
		);

		$('#showFieldsToFixBalance').on('click', function (e) {
			$(".fixBalanceAdherentFormPart").parent().parent().toggle();
		});
	}

	if($(".cancelRecurrentPaymentFormPart").length > 0) {
		if (!$(".cancelRecurrentPaymentFormPart").parent().parent().hasClass('has-error')) {
			$(".cancelRecurrentPaymentFormPart").parent().parent().hide();
		}

		// Add descriptive text
		$(".cancelRecurrentPaymentFormPart").first().parent().parent().prepend( 
			`<p class="help-block">${$(".recurrentPaymentReason").first().val()}</p> <p class="help-block">Cette action va indiquer au kohinos que le paiement récurrent Payzen a été résilié manuellement de façon anticipée.</p>`

		)

		// Add hide/show button with event handler
		$(".cancelRecurrentPaymentFormPart").first().parent().parent().before(
			"<div class='form-group'><input class='btn btn-primary' type='button' id='showFieldsToCancelRecurringPayment' value='Afficher les champs pour annuler le paiment récurrent en cours'></input></div>"
		);

		$('#showFieldsToCancelRecurringPayment').on('click', function (e) {
			$(".cancelRecurrentPaymentFormPart").parent().parent().toggle();
		});
	}
});
