/* =================
   MAPPED FIELD
   ================= */

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

export default class MappedField {
	
	$elem: JQuery = null;
	$mapDropdown: JQuery;
	$filtersIcon: JQuery;
	$formulaInput: JQuery;
	$statusIcon: JQuery;
	
	statusOn: string = 'atmi-checkmark-circle';
	statusOff: string = 'atmi-cross-circle';
	
	constructor(
		public field: Field,
		public entity: Entity,
		public fileColumns: string[],
		private globals: Globals,
		private settings: ExportSettings
	) {
		
		this.$elem = $(this.globals.$importMappingSection.find('#mapped-field-tmpl').html());
		this.$mapDropdown = this.$elem.find('select.map-field');
		this.$filtersIcon = this.$elem.find('.with-filters');
		this.$formulaInput = this.$elem.find('.formula');
		this.$statusIcon = this.$elem.find('.status');
		
		this.prepareField();
		
	}
	
	/**
	 * Prepare the mapped field for the DOM
	 */
	prepareField() {
		
		// Add the data to the mapped field.
		this.$elem.find('.mapped-field--template').html(`
			<span class="entity-label atum-tooltip" title="${ this.settings.get( this.entity.isMain ? 'mainEntity' : 'subentities' ) }">${ this.entity.title }</span>
			<span class="field-label atum-tooltip" title="${ this.field.label ? `${ this.field.label } (${ this.field.name })` : this.field.name }">${ this.field.label || this.field.name }</span>
		`);
		
		// Fill in the mapping dropdown with all the coming file columns.
		this.fileColumns.forEach( (value: string) => {
			this.$mapDropdown.append(`<option value="${ value }"${ this.field.name === value || this.field.settings.column_name === value ? ' selected="selected"' : '' }>${ value }</option>`);
		});
		
		// Set the status icon.
		if (this.$mapDropdown.val()) {
			this.$statusIcon.removeClass( this.statusOff ).addClass( this.statusOn );
		}
		
		// Set the filters icon.
		if (typeof this.field.filters !== 'undefined' && this.field.filters.length) {
			this.$filtersIcon.addClass('with-filters');
		}
		
		// Add the Select2.
		this.globals.enhancedSelect.doSelect2(this.$elem.find('.atum-select2'));
	
	}

}