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

/** USER SETTINGS **/
//Enregistrement des préférences utilisateur
function sendmail_user_save_preference(){
	$.action({
		action: 'sendmail_user_save_preference',
		preferences: $('#sendmail-user-setting-form').toJson()
	},function(){
		$.message('success','Enregistré');
	});
}

/** MAIL **/
//Ajout d'un contact
function sendmail_contact_add(from,data){
	var modal = $('#sendmail-modal');
	if(!from) from = $('.recipientLine:eq(0)',modal);

	recipientVal = $('.recipient',from).val();
	var clone = recipientVal != '' ? from.clone() : from;
	if(recipientVal != '') clone.addClass('offset-md-2');
	clone.find('.typeahead.dropdown-menu').remove();

	var component = clone.find('select[data-type="dropdown-select"]');
	if(recipientVal != '') clone.find('div.recipient-type.data-type-dropdown-select').remove();
	component.removeClass('hidden');
	init_components(component);

	var input = clone.find('.recipient');
	input.val('');
	$('.recipientBox',modal).append(clone);
	input.focus();

	var type = from.find('.recipient-type .dropdown-menu .dropdown-item.active').attr('data-value');
	clone.find('.recipient-type').val(type);

	if(data){
		input.val(data.mail);
		clone.find('.recipient-type').val(data.type);
	}
	var options = $('#sendmail-modal').data('data');
	if(options && options.recipientComplete) sendmail_autocomplete(options.recipientComplete);

	init_components('#sendmail-modal');
}

//Suppression d'un contact
function sendmail_contact_delete(from){
	var modal = $('#sendmail-modal');
	if($('.recipientLine',modal).length<=1){
		$('.recipientLine .recipient',modal).val('').focus();
		return;
	}
	$(from).closest('.recipientLine').remove();
	$('.recipientLine:first-of-type',modal).removeClass('offset-md-2');
}

//Envoi d'un mail
function sendmail_send(data,callback){
	if(isProcessing) return;
	isProcessing = true;
		var modal = $('#sendmail-modal');
		if(!$('#subject',modal).val().length && !confirm("Le message n'a pas de sujet.\nEnvoyer quand-même ?")) return;
		if($('.btn-send', modal).hasClass('btn-preloader')) return;

		$('.btn-send', modal).addClass('btn-preloader');
		var recipients = {'to':[],'cc':[],'cci':[]};

		$('.recipientBox .recipientLine',modal).each(function(i,element){
			var line = $(element);
			var input = line.find('.recipient');

			if(!input.val().length) return;
			recipients[line.find('select.recipient-type').val()].push(input.val());
		});
		var attachments = $('#attachments_temporary',modal).val().length ? JSON.parse($('#attachments_temporary',modal).val()) : [];
		var data = $.extend(modal.data('data'),{
			action: 'sendmail_mail_send',
			from: $('#from',modal).val(),
			origin: data.origin,
			recipient: recipients,
			subject: $('#subject',modal).val(),
			files: JSON.stringify(attachments),
			message: $('#message',modal).val(),

		});
		$.action(data,function(r){
			$.message('info', r.message);
			modal.modal('hide');
			isProcessing = false;

			if(callback){
				if(typeof callback == 'string' && window[callback]!=null){
					window[callback](r);
				}else{
					callback(r);
				}
			}
		}, function(){
			isProcessing = false;
		});
}

function sendmail_autocomplete(data){
	var modal = $('#sendmail-modal');

	$('.recipient',modal).autocomplete({
		action : data.action,
		data : data.data,
		force : false,
		skin : function(item,input){
			var re = new RegExp(input.val(),"gi");

			name = item.name.replace(re, function(x) {
				return '<strong>'+x+'</strong>';
			});
			mail = item.mail ? item.mail.replace(re, function(x) {
				return '<strong>'+x+'</strong>';
			}) : '';

			return '<span class="sendmail-autocomplete-line"><span class="sendmail-autocomplete-label">'+name+
			'</span> <span class="sendmail-autocomplete-mail">&lt;'+mail+'&gt;</span></span>';
		},
		highlight : function(item){
			return item;
		},
		onClick : function(selected,element){
			element.val(selected.id);
			sendmail_contact_add(element.closest('.recipientLine'));
			element.closest('.recipientLine').next('li').focus();

		}
	});

}

//Edition d'un mail
/* Le parametre data peut contenir les parametres suivants :
	* from : valeur de l'adresse de l'expediteur à l'affichage
	* subject : valeur de l'objet à l'affichage
	* message : valeur du message à l'affichage
	* attachments : pièces jointes a afficher lors de la preview au format
				[{
					path : 'contact/documents/12/myFile.docx',
					url : 'action.php?action=contact_download_document&path=myfile.docx',
					name : 'myFile.docx',
					icon : 'far fa-file-archive text-warning'
				}]

	* signature (true/false): si la signature est à false, on ajoutera pas automatiquement la signature par défaut au message (défaut true)
 	* recipients : auto-rempli les destinataires, le parametre doit être au format {'to':[],'cc':[],'cci':[]};
 	* recipientComplete : Si une action est spécifiée, l'autocomplete sur les récipient est activé, l'action recoit le parametre "keyword" et doit retourner les
	résultats au format: { rows : [{id:'mail@mail.com',name:'John DOE','mail':'mail@mail.com'}]
*/
function sendmail_preview(data, onPreviewComplete, onSendComplete){
	$('#sendmail-modal').remove();

	if(!data) data = {};
	$(window).on('shown.bs.modal', function (e) {
		var modal = $('#sendmail-modal');
	  	if(data.attachments){
			$('#attachments', modal).replaceWith(('<div data-type="dropzone" data-label="Faites glisser vos pièces jointes ici" data-delete="dropzone_delete_file" class="form-control w-100 h-100 mb-2" id="attachments" name="attachments"></div>'));
			$('#attachments', modal).html(JSON.stringify(data.attachments));
		}
		init_components(modal);

		//On set les documents en PJ pré-settés pour gérer la suppression par la suite
		if(data.attachments) $('#attachments_temporary', modal).val(JSON.stringify(data.attachments));
		if(onPreviewComplete) onPreviewComplete(data);
	});

	$.ajax({
		url: 'action.php?action=sendmail_mail_preview',
		data: data,
		method : 'POST',
		success: function(response){
			$('body').append(response);
			var modal = $('#sendmail-modal');

			if(data.recipients){
				var types = ['to','cc','cci'];
				for (var u in types) {
					var type = types[u];
					for (var i in data.recipients[type]) {
						sendmail_contact_add(null,{
							type : type,
							mail : data.recipients[type][i]
						});
					}
				}
			}
			modal.modal('show');
			modal.data('data',data);

			var form = $('#sendForm',modal);
			form.on('click','.recipientBox .recipient-type .dropdown-menu a',function(){
				var target = $(this);
				var recipientBox = target.closest('.recipientBox');

				$('.recipient', recipientBox).attr('data-type',target.attr('data-value')).focus();
				recipientBox.find('.recipientType').text(target.html());
			}).on('keydown','.recipient',function(e){
				if(['+',',',';','Enter'].indexOf(e.key)>=0) {
					e.preventDefault();
					sendmail_contact_add($(this).closest('.recipientLine'));
				}
			});

			if(data.recipientComplete) sendmail_autocomplete(data.recipientComplete);

			modal.on('keyup', 'input, textarea, *[contenteditable="true"]', function(e){
				//Press Del (touche "Suppr")
				if(e.keyCode == 46) e.stopPropagation();
			})

			$('.btn-send',modal).click(function(){
				sendmail_send(data,onSendComplete);
			});

			$('.trumbowyg-editor', modal).on('keyup',function(event){
				//Press Ctrl + Enter
				if(event.keyCode == 13 && event.ctrlKey)
					$(this).trigger('insertCarriageReturn');
			});
		}
	});
}