/* ================
   ENTITY SELECTOR
   ================ */

import ExportSettings from '../../config/_export-settings';
import Globals from './_globals';
import Progress from './_progress';
import { Blocker } from '../../../../../../atum-stock-manager-for-woocommerce/assets/js/src/components/_blocker';

export default class EntitySelector {
	
	$elem: JQuery;
	$entityLabel: JQuery = null;
	entitySelected: string;
	entitySelectedName: string;
	entityData: any = null;

	constructor(
		private settings: ExportSettings,
		private globals: Globals
	) {
		
		this.$elem = this.globals.$entitySection.find('#entity-selector');
		this.globals.progress = new Progress(this.globals);
		
		// Add the select2.
		this.globals.enhancedSelect.doSelect2(this.$elem);
	
		this.bindEvents();
		
	}
	
	bindEvents() {
		
		// Listen for entity changes.
		this.$elem.on('change', (evt: JQueryEventObject) => {
			
			this.entitySelected = $(evt.currentTarget).val();
			
			if (this.entitySelected) {
				this.entitySelectedName = this.$elem.find(`option[value="${ this.entitySelected }"]`).text();
				this.selectEntity();
			}
			
		}).change(); // Force the change in case an existing template is being loaded.
		
		// Unselect the current entity.
		this.globals.$entitySection.on('click', '.unselect-entity', () => {
			
			// If there are no selected fields, there is no need to show the alert.
			if (this.globals.hasSelectedFields()) {
				
				this.globals.swal({
					title            : this.settings.get('areYouSure'),
					text             : this.settings.get('removeEntity'),
					type             : 'warning',
					showCancelButton : true,
					confirmButtonText: this.settings.get('continue'),
					cancelButtonText : this.settings.get('cancel'),
					reverseButtons   : true,
					allowOutsideClick: false
				})
				.then( () => this.unselectEntity() )
				.catch(this.globals.swal.noop);
				
			}
			else {
				this.unselectEntity();
			}
			
		});
		
	}
	
	/**
	 * Perform actions after selecting an entry from the list
	 */
	selectEntity() {
		
		$.ajax({
			url       : window['ajaxurl'],
			dataType  : 'json',
			method    : 'post',
			data      : {
				action     : 'aep_get_entity_data',
				token      : this.settings.get('nonce'),
				entity     : this.entitySelected,
				template_id: this.globals.templateId,
			},
			beforeSend: () => Blocker.block(this.globals.$contentWrapper),
			success   : (response: any) => {
				
				if (response.success === true) {
					this.entityData = response.data || {};
					this.showSelectedLabel();
					
					// Allow listening for entity data changes externally.
					this.$elem.trigger('atum-export-entity-data-loaded', [this.entityData]);
					this.globals.progress.setStep( this.globals.templateId ? 2 : 1 );
				}
				else {
					this.unselectEntity();
				}
				
				Blocker.unblock(this.globals.$contentWrapper);
				
			},
			error     : () => {
				this.unselectEntity();
				Blocker.unblock(this.globals.$contentWrapper);
			},
		});
	
	}
	
	/**
	 * Show a label and hide the selector when an entity is selected
	 */
	showSelectedLabel() {
	
		this.$elem.siblings('.select2-container').hide();
		this.$entityLabel = $(`<div class="entity-selected" data-entity="${ this.entitySelected }">${ this.entitySelectedName } <i class="atum-icon atmi-cross-circle unselect-entity"></i></div>`);
		this.$entityLabel.insertAfter(this.$elem);
	
	}
	
	/**
	 * Unload the selected entity
	 */
	unselectEntity() {
		
		if (this.$entityLabel !== null) {
			this.$entityLabel.remove();
		}
		
		this.$elem.val('').change()
			.siblings('.select2-container').show();
		
		this.entityData = null;
		
		// Allow listening for entity data changes externally.
		this.$elem.trigger('atum-export-entity-data-unloaded');
		
		// Reset the progress.
		this.globals.progress.setStep(0);
		
	}

}