EpnTapModule.js 12 KB
/**
 * Project  : AMDA-NG
 * Name	 : EpnTapModule.js
 * @class   amdaDesktop.EpnTapModule
 * @extends amdaDesktop.AmdaModule
 * @brief   EpnTap Module controller definition
 * @author  Nathanael Jourdane
 */

Ext.define('amdaDesktop.EpnTapModule', {

	extend: 'amdaDesktop.AmdaModule',
	requires: ['amdaUI.EpnTapUI'],
	contentId : 'EpnTapUI',

	/** The alias name of the module view. */
	// uiType: 'panelEpnTap',
	uiType : 'panelEpnTap',

	/** The text displayed on the *help button* tooltip. */
	helpTitle: 'Help on EPN-TAP Module',

	/** The name of the documentation file related to the module. */
	helpFile : 'epnTapHelp',

	/**
	Module initialisation. Called the first time that the user open the epnTap module.
	*/
	init: function() {
		this.filter = Array();
		this.selectedServiceId = null;

		this.launcher = {
			text: this.title,
			iconCls: this.icon,
			handler: this.createWindow,
			scope: this
		};

		this.aquireElements();

		// create productTypeDict based on productTypesStore
		this.productTypesStore.on({
			load: function(store) {
				this.productTypeDict = {};
				for (var key in store.data.map) {
					this.productTypeDict[key] = store.data.map[key].data.name;
				}
			},
			scope: this
		});

		this.servicesStore.load();
		this.productTypesStore.load();
	},

	aquireElements: function() {
		// UI elements
		this.servicesGrid = Ext.getCmp('epnTapServicesGrid');
		this.granulesGrid = Ext.getCmp('epnTapGranulesGrid');
		this.productTypeCB = Ext.getCmp('epnTapProductTypeCB');
		this.targetNameCB = Ext.getCmp('epnTapTargetNameCB');
		this.timeSelector = Ext.getCmp('epnTapTimeSelector');
		this.rowsPerPageNf = Ext.getCmp('epnTapRowsPerPageNf');
		this.currentPageLb = Ext.getCmp('epnTapCurrentPageLb');
		this.totalPagesLb = Ext.getCmp('epnTapTotalPagesLb');
		this.firstPageBtn = Ext.getCmp('epnTapFirstPageBtn');
		this.previousPageBtn = Ext.getCmp('epnTapPreviousPageBtn');
		this.nextPageBtn = Ext.getCmp('epnTapNextPageBtn');
		this.lastPageBtn = Ext.getCmp('epnTapLastPageBtn');

		// stores elements
		this.servicesStore = Ext.data.StoreManager.lookup('servicesStore');
		this.granulesStore = Ext.data.StoreManager.lookup('granulesStore');
		// this.metadataStore = Ext.data.StoreManager.lookup('metadataStore')
		this.productTypesStore = Ext.data.StoreManager.lookup('productTypesStore');
		this.targetNamesStore = Ext.data.StoreManager.lookup('targetNamesStore');
	},

	addUIListeners: function() {
		this.servicesGrid.on('cellclick', function(grid, td, cellIndex, record) {
			this.onServiceSelected(record.data['id']);
		}, this);

		this.granulesGrid.on('cellclick', function(grid, td, cellIndex, record) {
			this.onGranuleSelected(record.data['id']);
		}, this);

		this.firstPageBtn.on('click', function() {
			this.onFirstPageBtnClicked();
		}, this);

		this.previousPageBtn.on('click', function() {
			this.onPreviousPageBtnClicked();
		}, this);

		this.nextPageBtn.on('click', function() {
			this.onNextPageBtnClicked();
		}, this);

		this.lastPageBtn.on('click', function() {
			this.onLastPageBtnClicked();
		}, this);
	},

	/**********************
	*** Utils functions ***
	**********************/

	/**
	Capitalize a name and replace underscores with spaces.
	- `name`: The string to make pretty.
	*/
	prettify: function(name) {
		return name.charAt(0).toUpperCase() + name.replace(/_/g, ' ').substr(1).toLowerCase();
	},

	/**
	Capitalize a name, replace underscores with spaces, and write it in a plurial form.
	- `name`: The string to make pretty.
	*/
	allPrettify: function(name) {
		return 'All ' + (name[name.length-1] == 's' ? name : name + 's').replace(/_/g, ' ').toLowerCase();
	},

	isDate: function(date) {
		if (date === null) {
			return false;
		}
		var dateArr = date.split('/');
		if (dateArr.length != 3 || isNaN(parseInt(dateArr[0])) || isNaN(parseInt(dateArr[1])) || isNaN(parseInt(dateArr[2])) ) {
			return false;
		}
	return true;
	},

	/**
	Disable or enable the navigation buttons (see `EpnTapUI.createNavigationPanel()`).
	*/
	disableNavBtns: function(firt, previous, next, last) {
		this.firstPageBtn.setDisabled(firt);
		this.previousPageBtn.setDisabled(previous);
		this.nextPageBtn.setDisabled(next);
		this.lastPageBtn.setDisabled(last);
	},

	/****************************
	*** Service filter events ***
	****************************/

	/**
	Called each time the epntap module is loaded.
	- `target`: an array of 3 values: [target_name, dataproduct_type]; or null.
	*/
	loadTarget: function(target) {
		this.target = target;
		this.aquireElements();
		this.addUIListeners();

		// this.servicesStore.clearFilter();
		this.granulesStore.removeAll();

		if(target) {
			this.targetNameCB.getStore().add({'id': target[0], 'name': this.prettify(target[0])});
			this.targetNameCB.select(target[0]);
			this.productTypeCB.select(target[1]);
			this.updateNbResults();
		}
	},

	/*********************
	*** Buttons events ***
	*********************/

	/**
	Trigerred when the `firstPageBtn` button is clicked (see `EpnTapUI.createNavigationPanel()`). Among other things,
	send a new query and fill `granulesGrid`.
	*/
	onFirstPageBtnClicked: function() {
		var newPageNumber = 1;
		var limit = Number(this.rowsPerPageNf.value);
		var offset = 0;
		var selectedService = this.servicesStore.findRecord('id', this.selectedServiceId).data;

		this.disableNavBtns(true, true, false, false);
		this.currentPageLb.setText('' + newPageNumber);
		loadMask.show();
		AmdaAction.epnTapGetGranules(selectedService['table_name'], selectedService['access_url'], this.filter, limit, offset, this.fillGranules);
	},

	/**
	Trigerred when the `previousPageBtn` button is clicked (see `EpnTapUI.createNavigationPanel()`). Among other things,
	send a new query and fill `granulesGrid`.
	*/
	onPreviousPageBtnClicked: function() {
		var newPageNumber = Number(this.currentPageLb.text) - 1;
		var limit = Number(this.rowsPerPageNf.value);
		var offset = (newPageNumber-1) * limit;
		var selectedService = this.servicesStore.findRecord('id', this.selectedServiceId).data;

		this.currentPageLb.setText('' + newPageNumber);
		var isFirstPage = this.currentPageLb.text === '1';
		this.disableNavBtns(isFirstPage, isFirstPage, false, false);
		loadMask.show();
		AmdaAction.epnTapGetGranules(selectedService['table_name'], selectedService['access_url'], this.filter, limit, offset, this.fillGranules);
	},

	/**
	Trigerred when the `nextPageBtn` button is clicked (see `EpnTapUI.createNavigationPanel()`). Among other things,
	send a new query and fill `granulesGrid`.
	*/
	onNextPageBtnClicked: function() {
		var newPageNumber = Number(this.currentPageLb.text) + 1;
		var limit = Number(this.rowsPerPageNf.value);
		var offset = (newPageNumber-1) * limit;
		var selectedService = this.servicesStore.findRecord('id', this.selectedServiceId).data;

		this.currentPageLb.setText('' + newPageNumber);
		var isLastPage = this.currentPageLb.text == this.totalPagesLb.text;
		this.disableNavBtns(false, false, isLastPage, isLastPage);
		loadMask.show();
		AmdaAction.epnTapGetGranules(selectedService['table_name'], selectedService['access_url'], this.filter, limit, offset, this.fillGranules);
	},

	/**
	Trigerred when the `lastPageBtn` button is clicked (see `EpnTapUI.createNavigationPanel()`). Among other things,
	send a new query and fill `granulesGrid`.
	*/
	onLastPageBtnClicked: function() {
		var newPageNumber = Number(this.totalPagesLb.text);
		var limit = Number(this.rowsPerPageNf.value);
		var offset = (newPageNumber-1) * limit;
		var selectedService = this.servicesStore.findRecord('id', this.selectedServiceId).data;

		this.currentPageLb.setText('' + newPageNumber);
		this.disableNavBtns(false, false, true, true);
		loadMask.show();
		AmdaAction.epnTapGetGranules(selectedService['table_name'], selectedService['access_url'], this.filter, limit, offset, this.fillGranules);
	},

	/*******************
	*** Grids events ***
	*******************/

	/**
	Trigerred when a row is clicked in `servicesGrid` table (see `EpnTapUI.createServicesGrid()`). Among other things,
	send a new query and fill `granulesGrid`.
	*/
	onServiceSelected: function(selectedServiceId) {
		// console.log("Selected service " + selectedServiceId);
		var selectedService = this.servicesStore.findRecord('id', selectedServiceId).data;

		this.selectedServiceId = selectedServiceId;
		if (selectedService == null) {
			throw this.selectedServiceId + ' not found in the list of services.';
			return;
		}

		this.filter = Array(
			this.targetNameCB.value === 'all' ? null : this.targetNameCB.value, // target name
			this.productTypeCB.value === 'all' ? null : this.productTypeCB.value, // product type
			Ext.Date.format(this.timeSelector.getStartTime(), 'd/m/Y H:i:s'), // start time
			Ext.Date.format(this.timeSelector.getStopTime(), 'd/m/Y H:i:s') // stop time
		);

		loadMask.show();
		AmdaAction.epnTapGetNbRows(selectedService['table_name'], selectedService['access_url'], this.filter, this.updateNbRows);
		AmdaAction.epnTapGetGranules(selectedService['table_name'], selectedService['access_url'], this.filter, this.rowsPerPageNf.value, 0, this.fillGranules);
	},

	/**
	Trigerred when a row is clicked in `granulesGrid` table (see `EpnTapUI.createGranulesGrid()`). Do nothing yet, used
	for debug purposes only.
	*/
	onGranuleSelected: function(granule) {
		// console.log('selected granule: ', granule);
	},

	/**********************
	*** Other functions ***
	**********************/

	/**
	Update the nb_result field of the services store (see `EpnTapUI.servicesStore`), according to the field values in `serviceFilterPanel`.
	*/
	updateNbResults: function() {
		if(this.productTypeCB.value === 'all' && !this.launchedFromTree ) {
			var filter = [
				{property: "dataproduct_type", value: this.productTypeCB.value}
			];
		} else if(this.targetNameCB.value === 'all') {
			var filter = [
				{property: "dataproduct_type", value: this.productTypeCB.value}
			];
		} else {
			var filter = [
				{property: "dataproduct_type", value: this.productTypeCB.value},
				{property: "target_name", value: this.targetNameCB.value}
			];
		}

		// this.servicesStore.each(function(record, idx) {
		// 	this.metadataStore.filter(filter.concat({property: 'service_id', value: record.get('id')}));
		// 	record.set('nb_results', this.metadataStore.sum('nb_results'));
		// 	this.metadataStore.clearFilter();
		// }, this);
		// this.servicesStore.sort('nb_results', 'DESC');
		//
		// var timeMin = this.metadataStore.min('time_min');
		// var timeMax = this.metadataStore.max('time_max');
		this.timeSelector.setLimits(timeMin, timeMax);
		this.timeSelector.setInterval(timeMin, timeMax);
	},

	/**
	Callback function, called from the PHP script when the query result is received, when a service is selected.

	Among other things, update the `epnTapCurrentPageLb` label (see `EpnTapUI.createNavigationPanel()`).
	*/
	updateNbRows: function(nb_results) {
		var totalPages = Math.ceil(Number(nb_results) / Ext.getCmp('epnTapRowsPerPageNf').value);

		Ext.getCmp('epnTapCurrentPageLb').setText(totalPages == 0 ? '-' : '1');
		Ext.getCmp('epnTapTotalPagesLb').setText(totalPages == 0 ? '-' : totalPages);

		Ext.getCmp('epnTapPreviousPageBtn').setDisabled(true);
		Ext.getCmp('epnTapFirstPageBtn').setDisabled(true);
		Ext.getCmp('epnTapNextPageBtn').setDisabled(totalPages <= 1);
		Ext.getCmp('epnTapLastPageBtn').setDisabled(totalPages <= 1);
	},

	/**
	Callback function, called from the PHP script when the query result is received, when a service is selected or a
	navigation button is clicked.

	Among other things, fill the `epnTapGranulesGrid` table (see `EpnTapUI.granulesStore`).
	*/
	fillGranules: function(granules) {
		loadMask.hide();

		if (granules["error"] != null) {
			console.log('Can not get request response:', granules["error"]);
			if(granules["error"] == "no result") {
				Ext.Msg.alert('There is no result for this query.');
			} else {
				Ext.Msg.alert('Can not display granules due to an error from the selected epn-tap service.');
			}
		} else {
			try {
				Ext.getCmp('epnTapGranulesGrid').getStore().removeAll();
				Ext.getCmp('epnTapGranulesGrid').getStore().add(granules);
			} catch( e ) {
				console.log('Can not add granules: ' + e);
				Ext.Msg.alert('Can not display granules due to an error from the selected epn-tap service.');
			}
		}
	}
});