/* globals GravityKit, jQuery, List */
/**
 * Setups the variable holding the Stuff in the actions folder.
 *
 * @since TBD
 *
 * @type   {Object}
 */
GravityKit.GravityActions.Actions = GravityKit.GravityActions.Actions || {};

/**
 * Setups the main variable for this file.
 *
 * @since TBD
 *
 * @type   {Object}
 */
GravityKit.GravityActions.Actions.Email = {};

/**
 * Initialize the main part of this class.
 *
 * @since TBD
 *
 * @param  {Object} $   jQuery
 * @param  {Object} obj GravityKit.GravityActions.Trigger
 *
 * @return {void}
 */
( function ( $, obj ) {
	'use strict';

	/**
	 * Which action this Object is responsible for.
	 *
	 * @since TBD
	 *
	 * @type {string}
	 */
	obj.action = 'gk-bulk-email';

	/**
	 * Selectors used for configuration and setup.
	 *
	 * @since TBD
	 *
	 * @type {Object}
	 */
	obj.selectors = {
		entryListForm: '#entry_list_form',
		selectedFieldRadio: '.gk-gravityactions-send_to input',
		selectedFieldCount: '.gk-gravityactions-email-selected-field-count',
		entryCheckbox: '.gform_list_checkbox',
	};

	/**
	 * Local alias for the GA Hooks.
	 *
	 * @since TBD
	 *
	 * @type {(function(): Hooks)|*}
	 */
	obj.hooks = window.GravityKit.GravityActions.hooks;

	/**
	 * When the action is submitted from the bulk actions dropdown we trigger this.
	 *
	 * @since TBD
	 *
	 * @param {Event} event
	 * @param {Array} entries
	 * @param {Object} data
	 * @param {Event} originalEvent
	 */
	obj.onActionSubmit = ( event, entries, data, originalEvent ) => {
		if ( obj.action !== data.action ) {
			return;
		}

		let args = {
			view: 'email/step-1',
			entries: entries,
			form_id: data.formID,
			bulk_action: data.action,
			is_all_entries: obj.isAllEntries(),
			current_query_args: window.location.search.substring( 1 ),
		};

		args[ data.nonceName ] = data.nonce;

		GravityKit.GravityActions.Modal.request( args );
	};

	/**
	 * What should we to switch to the complete step.
	 *
	 * @since TBD
	 *
	 * @param formID
	 * @param entries
	 * @param action
	 * @param nonce
	 * @param nonceName
	 */
	obj.onCompleteUpdating = ( formID, entries, action, nonce, nonceName ) => {
		let args = {
			view: 'email/step-complete',
			is_all_entries: obj.isAllEntries(),
			entries: entries,
			form_id: formID,
			bulk_action: action,
			current_query_args: window.location.search.substring( 1 ),
		};

		args[ nonceName ] = nonce;

		GravityKit.GravityActions.Modal.request( args );
	};

	/**
	 * Determines if are selecting all entries.
	 *
	 * @since TBD
	 *
	 * @returns {string|*|jQuery}
	 */
	obj.isAllEntries = () => {
		const $allEntries = $( '#all_entries' );
		return $allEntries.val();
	};

	/**
	 * Handling of the next processing page.
	 *
	 * @since TBD
	 *
	 * @param formID
	 * @param entries
	 * @param action
	 * @param nonce
	 * @param nonceName
	 * @param currentPage
	 * @param fieldValues
	 */
	obj.handleNextPage = ( formID, entries, action, nonce, nonceName, currentPage, fieldValues ) => {
		let args = {
			view: 'email/step-processing',
			is_all_entries: obj.isAllEntries(),
			entries: entries,
			current_page: currentPage,
			field_values: fieldValues,
			form_id: formID,
			bulk_action: action,
			current_query_args: window.location.search.substring( 1 ),
		};

		args[ nonceName ] = nonce;

		GravityKit.GravityActions.Modal.request( args );
	};

	/**
	 * Opens the Email Modal.
	 *
	 * @since TBD
	 *
	 * @param data
	 */
	obj.modalOpen = ( data ) => {
		const $mergeTags = $( '.merge-tag-support' );

		if ( $mergeTags.length >= 0 ) {
			window.form = gk_email.form;

			// Fix for default form without parameter id in the url in entries page.
			gf_vars.mergeTags = gk_email.merge_tags;

			$mergeTags.each( ( index, mergeTag ) => {
				new gfMergeTagsObj( window.form, $( mergeTag ) );
				$( '.tooltip-merge-tag' ).contents().filter( function () {
					return this.nodeType == 3 && this.textContent.trim();
				} )[ 0 ].textContent = '';
			} );
		}

		// Reinitialize the editor: Remove the editor then add it back
		const settings = {
			tinymce: {
				wpautop: true,
				plugins:
					'charmap colorpicker compat3x directionality fullscreen hr image lists media paste tabfocus textcolor wordpress wpautoresize wpdialogs wpeditimage wpemoji wpgallery wplink wptextpattern wpview',
				toolbar1:
					'bold italic underline strikethrough | bullist numlist | blockquote hr wp_more | alignleft aligncenter alignright | link unlink | fullscreen | wp_adv',
				toolbar2:
					'formatselect alignjustify forecolor | pastetext removeformat charmap | outdent indent | undo redo | wp_help',
			},
			quicktags: true,
			mediaButtons: true,
		};

		wp.editor.remove( 'message' );
		wp.editor.initialize( 'message', settings );

		// Tooltips
		gform_initialize_tooltips();

		$( obj.selectors.selectedFieldRadio ).filter( ':checked' ).trigger( 'change' );
	};

	/**
	 * When the select field is changed.
	 *
	 * @since TBD
	 *
	 * @param event
	 */
	obj.onFieldSelect = ( event ) => {
		let selectedValue = $( event.target ).val();
		if ( selectedValue === 'field' ) {
			$( '.gk-gravityactions-toField' ).removeClass( 'hidden' );
			$( '.gk-gravityactions-toEmail' ).addClass( 'hidden' );
			return;
		}

		if ( selectedValue === 'email' ) {
			$( '.gk-gravityactions-toEmail' ).removeClass( 'hidden' );
			$( '.gk-gravityactions-toField' ).addClass( 'hidden' );
			return;
		}
	};

	/**
	 * Handles the initialization of the manager when Document is ready.
	 *
	 * @since TBD
	 *
	 * @return {void}
	 */
	obj.ready = () => {
		$( GravityKit.GravityActions.Trigger.selectors.entryListForm ).on( 'submitBulkAction.GravityActions/GK', obj.onActionSubmit );
		$( document ).on( 'change.GravityActions/GK', obj.selectors.selectedFieldRadio, obj.onFieldSelect );
		$( document ).on( 'afterAjaxSuccess.GravityActions/GK', obj.modalOpen );
	};

	// Configure on document ready.
	$( obj.ready );
} )( jQuery, GravityKit.GravityActions.Actions.Email );