/* global devikitWfirmaOrderColumns */

( function( $ ) {
	'use strict';

	$( function() {
		$( document ).on( 'click', '.wfirma-download-pdf-link', function( e ) {
			e.preventDefault();

			var $link = $( this );
			var invoiceId = $link.data( 'invoice-id' );
			var invoiceNumber = $link.data( 'invoice-number' );
			var documentType = $link.data( 'document-type' ) || 'invoice';
			var originalText = $link.text();

			var ajaxUrl = ( devikitWfirmaOrderColumns && devikitWfirmaOrderColumns.ajaxUrl )
				? devikitWfirmaOrderColumns.ajaxUrl
				: ( typeof ajaxurl !== 'undefined' ? ajaxurl : '' );

			var nonce = devikitWfirmaOrderColumns && devikitWfirmaOrderColumns.nonce
				? devikitWfirmaOrderColumns.nonce
				: '';

			var downloadingText = devikitWfirmaOrderColumns && devikitWfirmaOrderColumns.i18n && devikitWfirmaOrderColumns.i18n.downloading
				? devikitWfirmaOrderColumns.i18n.downloading
				: 'Downloading...';

			var failedText = devikitWfirmaOrderColumns && devikitWfirmaOrderColumns.i18n && devikitWfirmaOrderColumns.i18n.failed
				? devikitWfirmaOrderColumns.i18n.failed
				: 'Failed to download PDF';

			$link.css( 'opacity', '0.5' ).text( downloadingText );

			$.post( ajaxUrl, {
				action: 'devikit_wfirma_download_pdf',
				invoice_id: invoiceId,
				invoice_number: invoiceNumber,
				document_type: documentType,
				nonce: nonce
			}, function( response ) {
				$link.css( 'opacity', '1' ).text( originalText );

				if ( response && response.success && response.data && response.data.pdf ) {
					var binary = atob( response.data.pdf );
					var array = new Uint8Array( binary.length );
					for ( var i = 0; i < binary.length; i++ ) {
						array[ i ] = binary.charCodeAt( i );
					}
					var blob = new Blob( [ array ], { type: 'application/pdf' } );
					var url = window.URL.createObjectURL( blob );
					var a = document.createElement( 'a' );
					a.href = url;
					a.download = response.data.filename;
					document.body.appendChild( a );
					a.click();
					window.URL.revokeObjectURL( url );
					document.body.removeChild( a );
				} else {
					var message = response && response.data && response.data.message ? response.data.message : failedText;
					window.alert( message );
				}
			} ).fail( function() {
				$link.css( 'opacity', '1' ).text( originalText );
				window.alert( failedText );
			} );
		} );
	} );
} )( jQuery );

