/* =====================
   EXPORT CENTRAL
   ===================== */

import ExportCenter from './_export-center';
import ExportSettings from '../../config/_export-settings';
import GettingStarted from './_getting-started';
import Globals from "./_globals";
import ImportCenter from './_import-center';
import TabLoader from '../../../../../../atum-stock-manager-for-woocommerce/assets/js/src/components/_tab-loader';
import Templates from './_templates';
import Tooltip from "../../../../../../atum-stock-manager-for-woocommerce/assets/js/src/components/_tooltip";
import { Utils } from '../../../../../../atum-stock-manager-for-woocommerce/assets/js/src/utils/_utils';

export default class Router {
	
	tabLoader: TabLoader;
	
	gettingStarted: GettingStarted;
	exportCenter: ExportCenter;
	templates: Templates;
	importCenter: ImportCenter;
	
	constructor(
		private settings: ExportSettings,
		private toolTip: Tooltip,
		private globals: Globals,
	) {
		
		this.setupNavigation();
		this.loadTabContent( Utils.getUrlParameter('tab') );
		
	}
	
	/**
	 * Load the tab content components
	 *
	 * @param {string} currentTab
	 */
	loadTabContent(currentTab: string) {
		
		this.globals.currentTab = currentTab ? currentTab : 'getting-started';
		
		// We need to initialize the global props for each tab.
		this.globals.initProps();
		
		switch (this.globals.currentTab) {
			
			// Export Center tab.
			case 'export-center':
				this.exportCenter = new ExportCenter(this.settings, this.globals);
				break;
			
			// Templates tab.
			case 'templates':
				this.templates = new Templates(this.settings, this.globals);
				break;
			
			// Import Center tab.
			case 'import-center':
				this.importCenter = new ImportCenter(this.settings, this.globals);
				break;
			
			// Getting Started tab.
			default:
				this.gettingStarted = new GettingStarted(this.settings, this.globals);
				break;
			
		}
		
		// Clen up any possible entity data that was previously loaded.
		if (this.exportCenter) {
			this.exportCenter.cleanUpEntity();
		}
		
		// Hide/Show the screen options.
		const $screenOptions: JQuery = $('#screen-options-link-wrap');
		if ('templates' === this.globals.currentTab) {
			$screenOptions.slideDown('fast');
		}
		else {
			$screenOptions.slideUp('fast');
		}
		
	}
	
	/**
	 * Set up the tab naviagation
	 */
	setupNavigation() {
		
		// Instantiate the loader to register the jQuery.address and the events.
		this.tabLoader = new TabLoader(this.globals.$wrapper, this.globals.$nav);
		
		// Tab clicked.
		this.globals.$wrapper.on('atum-tab-loader-clicked-tab', (evt: JQueryEventObject, $navLink: JQuery, tab: string) => {
			
			if ('export-center' === tab && this.globals.$wrapper.find('.export-content').hasClass('.dirty')) {
				
				// Warn the user about unsaved data.
				this.globals.swal({
					title            : this.settings.get('areYouSure'),
					text             : this.settings.get('unsavedData'),
					type             : 'warning',
					showCancelButton : true,
					confirmButtonText: this.settings.get('continue'),
					cancelButtonText : this.settings.get('cancel'),
					reverseButtons   : true,
					allowOutsideClick: false,
				})
				.then( () => this.moveToTab($navLink), (dismiss: string) => $navLink.blur() );
				
			}
			else {
				this.moveToTab($navLink);
			}
			
		});
		
	}
	
	/**
	 * Move to a new tab
	 *
	 * @param {JQuery} $navLink
	 */
	moveToTab($navLink: JQuery) {
		
		const tab: string = $navLink.data('tab');
		
		if (typeof tab === 'undefined') {
			return;
		}
		
		this.globals.currentTab = tab ? tab : 'getting-started';
		
		const $contentWrapper: JQuery = this.globals.$wrapper.children('.export-content-wrapper');
		
		this.globals.$nav.find('.nav-link')
			.filter( (index: number, elem: Element) => {
				return $(elem).parent().hasClass('active');
			} )
			.not($navLink).parent().removeClass('active');
		
		this.globals.tooltip.destroyTooltips(this.globals.$wrapper);
		$navLink.parent().addClass('active');
		$contentWrapper.addClass('overlay');
		
		// Change the page title.
		$('.wp-heading-inline').children('span').text( $.trim($navLink.text()) || this.settings.get('exportPro') );
		
		let url: string = $navLink.attr('href');
		const parameters: string[] = $.address.parameterNames();
		
		// Export tab params.
		if (this.globals.currentTab === 'export-center' && typeof $.address.parameter('template_id') !== 'undefined') {
			url += `&template_id=${ parseInt( $.address.parameter('template_id') ) }`;
		}
		// Templates tab params.
		else if (this.globals.currentTab === 'templates' && parameters.length) {
			
			for (const parameter of parameters) {
				url += `&${ parameter }=${ $.address.parameter(parameter) }`;
			}
			
		}
		
		$contentWrapper.load( `${ url } .export-content-wrapper > *`, () => {
			$contentWrapper.removeClass('overlay');
			this.loadTabContent( TabLoader.getCurrentTab() );
		});
		
	}
	
}
