var angular = require('cla_angular');

/**
 * The controller that handles datatable form
 *
 *
 */
(function () {
	'use strict';

	var moduleName = 'cla.core.dtform'; var module;
	try { module = angular.module(moduleName); }
	catch(err) { module = angular.module(moduleName, []); }

	module.controller('DtFormController', DtFormController);
	DtFormController.$inject = ['dtService'];

	/**
	 *
	 * @constructor
	 */
	function DtFormController(dtService) {
		var ctl = this;

		ctl.init = init;
		ctl.filter = filter;
		ctl.reset = reset;
		ctl.download = download;

		ctl.fields = {};

		var table_name;
		//////////////////

		function init(table) {
			table_name = table;
		}

		/**
		 * Run filter on the attached table
		 */
		function filter() {
			var service = dtService.get(table_name);
			service.filters = ctl.fields;
			service.build();
		}

		/**
		 * Reset filters on the attached table
		 * @param reload Whether to reload the page
		 */
		function reset(reload) {

			if (reload) {
				window.location.reload();
				return;
			}

			ctl.fields = {};

			var service = dtService.get(table_name);
			service.filters = ctl.fields;
			service.build();
		}

		/**
		 * Download table as csv format
		 */
		function download() {
			var service = dtService.get(table_name);
			service.filters = ctl.fields;
			service.download();
		}
	}
}());