/* =======================================
   ADD MAPPING COLUMN
   ======================================= */

import { Entity, Field } from '../../utils/_interfaces';
import ExportSettings from '../../config/_export-settings';
import Globals from './_globals';
import MappedField from './_mapped-field';

export default class AddMappingColumn {

	$button: JQuery;
	mappingColumnWizardTmpl: string;
	$selectFromDatabaseTmpl: JQuery;
	$createNewMetaTmpl: JQuery;
	
	constructor(
		private globals: Globals,
		private settings: ExportSettings
	) {
		
		this.$button = this.globals.$exportActions.find('#add-column');
		this.mappingColumnWizardTmpl = this.globals.$importMappingSection.find('#add-mapping-column-wizard-tmpl').html();
		this.$selectFromDatabaseTmpl = $( this.globals.$importMappingSection.find('#select-from-database-tmpl').html() );
		this.$createNewMetaTmpl = $( this.globals.$importMappingSection.find('#create-new-meta-tmpl').html() );
		
		this.bindEvents();
		
	}
	
	bindEvents() {
		
		// Start the wizard when the button is clicked.
		this.$button.on('click', (evt: JQueryEventObject) => {
			evt.preventDefault();
			this.startWizard();
		} );
		
	}
	
	/**
	 * Start the popup wizard
	 */
	startWizard() {
		
		this.globals.swal({
			title            : this.settings.get('addNewMappingColumn'),
			html             : this.mappingColumnWizardTmpl,
			showCancelButton : false,
			showConfirmButton: false,
			allowOutsideClick: false,
			showCloseButton  : true,
			width            : '530px',
			onOpen: (modal: Element) => {
				
				const $modal: JQuery = $(modal);
				
				$modal.find('#select-from-database').click( () => this.selectFromDatabase($modal) );
				$modal.find('#create-new-meta').click( () => this.createNewMeta($modal) );
				
			}
		})
		.catch(this.globals.swal.noop);
		
	}
	
	/**
	 * Add the UI to select a column from the available entities
	 */
	selectFromDatabase($modal: JQuery) {
		
		// Fill the select with all the available fields.
		const $select: JQuery = this.$selectFromDatabaseTmpl.find('#all-entity-fields');
		
		this.globals.entities.forEach( (entity: Entity) => {
			
			const $optGroup: JQuery = $(`<optgroup label="${ entity.title }" />`);
			$optGroup.data('entity', entity);
			
			const fields: Field[] = [ ...entity.fields, ...(entity.meta || []) ];
			
			fields.forEach( (field: Field) => {
				
				const fieldFound: MappedField[] = this.globals.mappedFields.filter( (mappedField: MappedField) => {
					return mappedField.entity.name === entity.name && mappedField.field.name === field.name && mappedField.field.group === field.group;
				} );
				
				// Only add the field to the list if is not already present.
				if (!fieldFound.length) {
					$(`<option value="${ field.name }">${ field.label || field.name }</option>`)
						.data('field', field)
						.appendTo($optGroup);
				}
				
			});
			
			$optGroup.appendTo($select);
			
		});
		
		this.globals.enhancedSelect.doSelect2( $select );
		
		$modal.find('.add-mapping-column-wizard').replaceWith( this.$selectFromDatabaseTmpl );
		
	}
	
	/**
	 * Add the UI to add a new custom meta
	 */
	createNewMeta($modal: JQuery) {
		
		// Fill the select with all the entities that support meta.
		const metaEntities: Entity[] = this.globals.entities.filter( (entity: Entity) => {
			return entity.has_meta === true;
		} );
		let $newMetaContent: JQuery;
		
		if (!metaEntities.length) {
			$newMetaContent = $(`<div class="alert alert-primary"><i class="atum-icon atmi-info"></i> ${ this.settings.get('noMetaEntities') }</div>`);
		}
		else {
			
			const $select: JQuery = this.$createNewMetaTmpl.find('#meta-entities');
			
			metaEntities.forEach( (entity: Entity) => {
				$(`<option value="${ entity.name }">${ entity.title }${ entity.isMain ? ` (${ this.settings.get('mainEntity') })` : '' }</option>`)
					.data('entity', entity)
					.appendTo($select);
			});
			
			$newMetaContent = this.$createNewMetaTmpl;
			this.globals.enhancedSelect.doSelect2( $select );
		
		}
		
		$modal.find('.add-mapping-column-wizard').replaceWith( $newMetaContent );
		
	}
	
}