/* ===============
   EXPORT SUMMARY
   =============== */

import ExportSettings from '../../config/_export-settings';
import Globals from './_globals';
import SelectedField from './_selected-field';

export default class Summary {
	
	selectedItems: number;
	$summaryTemplate: string;
	$summaryData: JQuery;
	
	constructor(
		private settings: ExportSettings,
		private globals: Globals,
	) {
		
		this.$summaryTemplate = this.globals.$summarySection.find('#summary-tmpl').html();
		this.$summaryData = this.globals.$summarySection.find('.summary-data');
		
		this.maybeCreateSummary();
		
	}
	
	/**
	 * Create the summary
	 */
	maybeCreateSummary() {
		
		this.selectedItems = $.isEmptyObject(this.globals.mainEntity) ? null : this.globals.mainEntity.selected;
	
		// If there is no data loaded yet, show the empty summary message.
		if (this.selectedItems === null) {
			this.addEmptySummary();
		}
		// Create and display the summary.
		else {
			this.updateSummary();
		}
		
	}
	
	/**
	 * Add the empty summary
	 */
	addEmptySummary() {
		this.$summaryData.html( this.globals.$summarySection.find('#empty-summary-tmpl').html() );
	}
	
	/**
	 * Update the summary data
	 */
	private updateSummary() {
		
		const $summary: JQuery        = this.globals.$summarySection.find('.ent-summary'),
		      $selectedFields: JQuery = this.globals.$selectedFieldsWrapper.find('.selected-field'),
		      $summaryFields: JQuery  = $summary.find('.ent-summary--fields');
		
		if ($selectedFields.length) {
		
			$summaryFields.empty();
			
			$selectedFields.each( (index: number, elem: Element) => {
				
				const $elem: JQuery                = $(elem),
				      selectedField: SelectedField = $elem.data('selected-field');
				
				$summaryFields.append(`
					<div class="selected-field-summary${ selectedField.filtersBuilder.hasRules() ? ' with-filters' : '' }${ !$elem.find('.field-visibility').is(':checked') ? ' no-visible' : '' }">
						<i class="atum-icon atmi-funnel"></i>
						<span class="entity-label">${ selectedField.entity.title }</span>
						<span class="field-label">${ selectedField.field.label }</span>
						${ !$elem.find('.field-visibility').is(':checked') ? ' <i class="atum-icon atmi-hidden"></i>' : '' }
					</div>
				`);
				
			});
			
			this.$summaryData.removeClass('no-selected-items');
			
		}
		else {
			this.$summaryData.addClass('no-selected-items').html( this.$summaryTemplate );
		}
		
		// Update the items' counter.
		$summary.find('.ent-summary--counters').html( this.settings.get('summaryItems').replace('%', this.selectedItems) );
		
		if (this.selectedItems === 0) {
			this.$summaryData.addClass('no-results');
		}
		else {
			this.$summaryData.removeClass('no-results');
		}
		
		// Check whether the current template is ready to export.
		this.globals.maybeIsReadyToExport();
	
	}
	
}