/* global jQuery, mairieAfficheInfoData */
( function ( $ ) {
	'use strict';

	$( function () {
		var $date    = $( '#mai-date' ),
			$texte   = $( '#mai-texte' ),
			$format  = $( '#mai-format' ),
			$apercu  = $( '#mai-apercu' ),
			$dl      = $( '#mai-telecharger' ),
			$btn     = $( '#mai-enregistrer' ),
			$spinner = $( '#mai-spinner' ),
			$msg     = $( '#mai-message' ),
			minuteur;

		if ( ! $date.length ) {
			return;
		}

		function parametres( extra ) {
			var p = {
				action: 'mairie_affiche_information_apercu',
				nonce: mairieAfficheInfoData.nonceApercu,
				date: $date.val(),
				format: $format.val()
			};
			if ( $.trim( $texte.val() ) !== '' ) {
				p.texte = $.trim( $texte.val() );
			}
			return $.extend( p, extra || {} );
		}

		function message( texte, type ) {
			$msg.attr( 'class', 'notice inline notice-' + type )
				.show()
				.find( 'p' ).text( texte );
		}

		function rafraichir() {
			$apercu.attr( 'src', mairieAfficheInfoData.ajaxUrl + '?' + $.param( parametres( { _: Date.now() } ) ) );
			$dl.attr( 'href', mairieAfficheInfoData.ajaxUrl + '?' + $.param( parametres( { dl: 1 } ) ) );
		}

		$date.on( 'change', rafraichir );
		$format.on( 'change', rafraichir );
		$texte.on( 'input', function () {
			clearTimeout( minuteur );
			minuteur = setTimeout( rafraichir, 400 );
		} );

		$btn.on( 'click', function () {
			$btn.prop( 'disabled', true ).text( mairieAfficheInfoData.msgEnCours );
			$spinner.addClass( 'is-active' );
			$msg.hide();

			$.post( mairieAfficheInfoData.ajaxUrl, {
				action: 'mairie_affiche_information_enregistrer',
				nonce: mairieAfficheInfoData.nonceEnreg,
				date: $date.val(),
				texte: $.trim( $texte.val() ),
				format: $format.val()
			} ).done( function ( reponse ) {
				if ( reponse && reponse.success ) {
					message( reponse.data.message, 'success' );
					$msg.find( 'p' ).append(
						' <a href="' + reponse.data.edit_url + '">' + mairieAfficheInfoData.msgOuvrir + '</a>' +
						' &middot; <a href="' + reponse.data.url + '" target="_blank" rel="noopener">' + mairieAfficheInfoData.msgVoir + '</a>'
					);
				} else {
					message( ( reponse && reponse.data && reponse.data.message ) || mairieAfficheInfoData.msgErreur, 'error' );
				}
			} ).fail( function () {
				message( mairieAfficheInfoData.msgErreur, 'error' );
			} ).always( function () {
				$btn.prop( 'disabled', false ).text( mairieAfficheInfoData.msgEnregistr );
				$spinner.removeClass( 'is-active' );
			} );
		} );

		rafraichir();
	} );
}( jQuery ) );
