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', '$timeout'];

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

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

		ctl.fields = {};

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

		function init(table, initial) {
			table_name = table;

            if (initial === undefined || initial.length === 0)
                return;

            // Merge initial values into form data
            $timeout(function(initial) {
                var service = dtService.get(table_name);
                for (var field in initial) {
                    if (initial.hasOwnProperty(field))
                        ctl.fields[field] = initial[field];
                }
                service.filters = ctl.fields;
                service.build();
            }, 0, true, initial);
		}

		/**
		 * 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();
		}
	}
}());
