/**
 * TasksPageCtrl Controller
 * Extracted from bookings module
 */

Bookings.controller('TasksPageCtrl', ['$scope', '$parse', 'Tasks', '$http', 'Client', 'Customer', 'ErrorsHandler', function ($scope, $parse, Tasks, $http, Client, Customer, ErrorsHandler) {



	/**
	 * holds selected data to be passed to clicked() function
	 *
	 * @type {{type: string, subtype: string, user: string, status: string, severity: string}}
	 */
	$scope.selections = {
		'user': '',
		'textSearch': '',
		'type': '',
		'subtype': '',
		'severity': '',
		'status': '',
		'myPaid': '',
		'myCompleted': '',
		'invoiced': '',
		'clientId': '',
		'customerId': '',
		'date': '',
	};


	/**
	  * @ $watchGroup | this was necessary to bind the ng-init calls to the backend to the front end once angular gets started
	  * if this is not done the whole thing (select inputs etc sit there and don't have any select options to choose from)
	  *
	  *
	  *
	  * @param [objects] selectInputs | this holds data for building the select inputs with ng-repeat
	  */

	$scope.$watchGroup(['users', 'types', 'subtypes', 'severities', 'statuses'], function () {

		// take only id and name from the ng-init on tasks.blade.php

		$scope.usersObject = $scope.makeControlObject($scope.users);
		$scope.typesObject = $scope.makeControlObject($scope.types);
		$scope.subtypesObject = $scope.makeControlObject($scope.subtypes);
		$scope.severitiesObject = $scope.makeControlObject($scope.severities);
		$scope.statusesObject = $scope.makeControlObject($scope.statuses);

		/**
		*
		* types mini-hack
		*
		  * mini hack to use name instead of id for types
		  *
		  * all other elements are bound to the database on their ids except types which keys off names (enum) - hardcoded into the db
		  *
		  * Vytas wrote it
		  */
		angular.forEach($scope.typesObject, function (key) {
			key.id = key.name;
		});

		$scope.selectInputs = [
			{
				name: 'user',
				label: 'User',
				icon: 'fa-user',
				model: 'user',
				values: $scope.usersObject
			},
			{
				name: 'type',
				label: 'Type',
				icon: 'fa-wrench',
				model: 'type',
				values: $scope.typesObject
			},
			{
				name: 'subtype',
				label: 'Subtype',
				icon: 'fa-bars',
				model: 'subtype',
				values: $scope.subtypesObject
			},
			{
				name: 'severity',
				label: 'Severity',
				icon: 'fa-exclamation-triangle',
				model: 'severity',
				values: $scope.severitiesObject
			},
			{
				name: 'status',
				label: 'Status',
				icon: 'fa-star',
				model: 'status',
				values: $scope.statusesObject
			}
		];
	});

	//    input type radio used in threes below drop down select boxes
	//
	$scope.radioInputs = [
		{
			model: 'myPaid',
			labelOne: 'All',
			labelTwo: 'Paid',
			labelThree: 'Unpaid',
			icon: 'fa-money'
		},
		{
			model: 'myCompleted',
			labelOne: 'All',
			labelTwo: 'Completed',
			labelThree: 'Open',
			icon: 'fa-list'
		},
		{
			model: 'date',
			labelOne: 'default',
			labelTwo: 'descending',
			labelThree: 'ascending',
			icon: 'fa-calendar-o'
		}

	];

	/*
	* associative array
	* holds task id's with their associated qa_ids
	* built up in makeQaTasks function
	*/
	$scope.qaTasks = [];

	/*
	/  make associative array from task id and qa_id
	*  used in ui grid to link qa status tasks to their actual qa task
	*/
	$scope.makeQaTasks = function (dataIn) {
		for (ctr in dataIn) {
			if (dataIn[ctr].qa_tasks.length > 0) {
				var qatask = dataIn[ctr].qa_tasks;
				var taskId = dataIn[ctr].id;
				for (ctr2 in qatask) {
					$scope.qaTasks[taskId] = qatask[ctr2].id; // associative array assignment
				}
			}
		}
	}

	/**
	* strips out unused data from server
	*
	* only name and id kept in most cases
	*/

	$scope.makeControlObject = function (collection) {
		var myObj = {};
		var myObjArray = [];
		angular.forEach(collection, function (key) {
			myObj = {
				id: '',
				name: ''
			};
			myObj.id = key.id;
			myObj.name = key.name;
			myObjArray.push(myObj);
		});
		return myObjArray;
	}


	/**
	 * passes the selections object to the main get request function
	 *
	 * @returns {{type: string, subtype: string, user: string, status: string, severity: string, myCompleted: number, myPaid: number, invoiced: number}|*|{type: string, subtype: string, user: string, status: string, severity: string}}
	 */
	$scope.getSelections = function () {
		return $scope.selections;
	};


	/**
	 * gets scope selections object  value at requested key
	 * @param key - key supplied by calling function at time of call
	 * @returns {*}
	 */
	$scope.getSelectionValue = function (key) {
		return $scope.selections[key];
	};

	$scope.setSelectionValue = function (key, value) {
		$scope.selections[key] = value;
	};


	$scope.clear = function ($event) {
		$event.stopPropagation();
		if ($scope.selections.textSearch || $scope.selections.textSearch.length > 0) {
			$scope.selections.textSearch = undefined;
		}
	};



	/**
	* reset a single selct drop down
	*
	* called when a red x appears after a selection next
	*
	* @param | control :
	*
	*/
	$scope.resetSingleSelect = function (control) {
		$scope.selections[control] = '';
	};


	/**
	 * itierates over scope.selections and resets all key values to ''
	 */
	$scope.resetSelectionsObject = function () {
		angular.forEach($scope.selections, function (key, value) {
			$scope.selections[value] = '';
		});
	};


	/**
	 * reset all selection object key/values
	 *
	 * @scope var selections - object to hold values selected in view options
	 */
	$scope.resetAll = function () {
		if (typeof $scope.selCliCust !== 'undefined') {
			$scope.selCliCust.selected = undefined;
		}
		$scope.resetSelectionsObject();
	};


	$scope.disabled = undefined;
	$scope.searchEnabled = undefined;
	$scope.searchRes = [];

	//client search
	$scope.searchMediaClient = function ($select) {

		return $http.get(Client.getSearchUrl(), {
			params: {
				name: $select.search
			}
		}).then(function (response) {
			$scope.searchRes = response.data.data;
			// $scope.clientSearch($scope.searchRes);
		});
	};

	$scope.onClientSelected = function (selectedClient, $select) {
		/**
		*
		* if undefined this means the built-in clear function was called by pressing the x that appears in the input box
		* after a selection is made
		* allowClear has to be set to true in the ui-select element for this - google it
		*/
		$scope.selCliCust = $select;
		if (typeof selectedClient !== 'undefined') {
			$scope.selections.clientId = selectedClient.id;
		}
		else {
			$scope.selections.clientId = '';
		}
	}

	//customer search
	$scope.searchMediaCustomer = function ($select) {
		return $http.get(Customer.getSearchUrl(), {
			params: {
				name: $select.search
			}
		}).then(function (response) {

			$scope.searchRes = response.data.data;
			// $scope.clientSearch($scope.searchRes);
		});
	};

	$scope.onCustomerSelected = function (selectedCustomer, $select) {
		// if undefined this means the built-in clear function was called by pressing the x that appears in the input box
		// after a selection is made
		// allowClear has to be set to true in the ui-select element for this - google it

		$scope.selCliCust = $select;
		if (typeof selectedCustomer !== 'undefined') {
			$scope.selections.customerId = selectedCustomer.id;
		}
		else {
			$scope.selections.customerId = '';
		}
	}

	/**
	 *  this builds the results table/grid
	 *
	 * @type {*[]} - array of objects holding various column/cell/grid
	 * options such as test
	 * parameters, widths, column labels
	 */
	$scope.columns = [
		{
			field: 'id',
			name: 'Id',
			width: '5%',
			cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()"><a ng-href="/tasks/{{COL_FIELD}}" title="Opens in new tab" target="_blank">{{COL_FIELD}}</a></div>',
			resizable: false
		},
		{
			field: 'client.name',
			name: 'Client',
			width: '17%',
			resizable: true
		},
		{
			field: 'title',
			name: 'Title',
			width: '17%',
			resizable: true
		},
		{
			field: 'created_at',
			name: 'Date Booked',
			width: '11%',
			type: 'date',
			cellFilter: "date:'dd/MM/yyyy'",
			enableFiltering: true,
			resizable: false
		},
		{
			field: 'user.name',
			name: 'Assigned To',
			width: '10%',
			resizable: true
		},
		{
			field: 'type',
			name: 'Type',
			width: '10%',
			resizable: true
		},
		{
			field: 'subtype_name',
			name: 'Subtype',
			width: '10%',
			resizable: true
		},
		{
			field: 'severity.name',
			name: 'Severity',
			width: '10%',
			resizable: true
		},
		{
			field: 'status.name',
			name: 'Status',
			width: '10%',
			cellTemplate: '<div class="ngCellText" ng-class="col.colIndex()"><a ng-if="(grid.appScope.qaTasks | contains : row.entity.id) == true" ng-href="/tasks/qa/{{grid.appScope.qaTasks[row.entity.id]}}" title="Opens in new tab" target="_blank">QC {{grid.appScope.qaTasks[row.entity.id]}}</a><span ng-if="(grid.appScope.qaTasks | contains : row.entity.id) == false">{{COL_FIELD}}</span></div>',
			resizable: true
		}
	];

	/**
	 * this configures the pagination options in ui-grid
	 *
	 * @type {{pageNumber: number, pageSize: number, sort: null, sortField: string}}
	 */
	var paginationOptions = {
		pageNumber: 1,
		pageSize: 100
	};
	/**
	 * this is a configuration object passed to the call to Tasks.get() api call in load and clicked function
	 * @type {{enableSorting: boolean, columnDefs: (any), onRegisterApi: $scope.gridOptions.onRegisterApi}}
	 */
	$scope.gridOptions = {
		enablePagination: true,
		enablePaginationControls: true,
		useExternalPagination: true,
		// useExternalSorting: true,
		paginationPageSizes: [20, 50, 100, 200],
		paginationPageSize: 100,
		enableFiltering: true,
		enableRowSelection: true,
		enableRowHeaderSelection: false,
		enableSelectAll: true,
		selectionRowHeaderWidth: 35,
		multiSelect: false,
		rowHeight: 35,
		showGridFooter: true,
		enableSorting: true,
		enableColumnResizing: true,

		//rowTemplate: '<div ng-dblclick="onDblClickRow(row)" ng-style="{ \’cursor\’: row.cursor }" ng-repeat="col in renderedColumns" ng-class="col.colIndex()" class="ngCell {{col.cellClass}}"><div class="ngVerticalBar" ng-style="{height: rowHeight}" ng-class="{ ngVerticalBarVisible: !$last }">&nbsp;</div><div ng-cell></div></div>',
		columnDefs: $scope.columns,
		onRegisterApi: function (gridApi) {
			$scope.gridApi = gridApi;
			gridApi.selection.on.rowSelectionChanged($scope, function (row) {
			});
			// $scope.gridApi.core.on.sortChanged($scope, function(grid, sortColumns) {
			// 	if (sortColumns.length == 0) {
			// 		paginationOptions.sort = null;
			// 	} else {
			// 		paginationOptions.sort = sortColumns[0].sort.direction;
			// 		paginationOptions.sortField = sortColumns[0].field;
			// 	}
			// 	$scope.loadData();
			// });
			gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
				paginationOptions.pageNumber = newPage;
				paginationOptions.pageSize = pageSize;
				$scope.loadData();
			});
		}
	};

	/**
	 * this is the main function
	 * when the show jobs button is clicked a 'get' request is sent with
	 * all the Tasks.get parameters
	 */

	$scope.loadData = function () {
		this.currentSelections = $scope.getSelections();
		var prams = {
			creator: true,
			client: true,
			user: true,
			severities: true,
			subtypes: true,
			textSearch: $scope.getSelectionValue('textSearch'),
			// orderBy: paginationOptions.sortField,
			// orderType: paginationOptions.sort,
			page: paginationOptions.pageNumber,
			qa: true,
			limit: paginationOptions.pageSize,
			type: $scope.getSelectionValue('type'),
			assigned_to: $scope.getSelectionValue('user'),
			// client_id: $scope.getSelectionValue('client'), will use later - nadeem	
			status: $scope.getSelectionValue('status'),
			subtype_id: $scope.getSelectionValue('subtype'),
			myCompleted: $scope.getSelectionValue('myCompleted'),
			myPaid: $scope.getSelectionValue('myPaid'),
			invoiced: $scope.getSelectionValue('invoiced'),
			clientId: $scope.getSelectionValue('clientId'),
			customerId: $scope.getSelectionValue('customerId')
		}
		if ($scope.selections.date == 1) {
			prams.orderBy = "created_at"
			prams.orderType = "asc"
		} else if ($scope.selections.date == 2) {
			prams.orderBy = "created_at"
			prams.orderType = "desc"
		}
		if ($scope.getSelectionValue('severity')) {
			prams.severity = $scope.getSelectionValue('severity')
		}
		for (var propName in prams) {
			if (prams[propName] === null || prams[propName] === undefined || prams[propName] === "") {
				delete prams[propName];
			}
		}
		Tasks.get(prams,

			function (response) {
				$scope.makeQaTasks(response.data);
				$scope.tasks = response.data;

				$scope.gridOptions.data = response.data;
				$scope.gridOptions.totalItems = response.total;

				angular.forEach($scope.gridOptions.data, function (task) {
					task.subtype_name = $scope.getSubtypeName(task.subtype_id); // link subtype id to subtype name
					task.created_at = $scope.dateFormat(task.created_at); // change JSON string to js Date() to enable sorting on date col
				});
			}, ErrorsHandler);
	};

	/**
	 * convert json string to date so grid date column becomes sortable
	 */
	$scope.dateFormat = function (date) {
		date = new Date(date);
		return date;
	};

	/**
	 * function to link subtype id to subtype name
	 *
	 * @param id
	 * @returns {string}
	 */
	$scope.getSubtypeName = function (id) {

		var name = 'not set';

		angular.forEach($scope.subtypes, function (subtype) {

			if (subtype.id == id) {
				name = subtype.name;
			}
		});
		return name;

	};

	$scope.$watch('selections', function () {
		$scope.loadData();
	}, true);

	// for V2
	// $scope.min = 50;
	// $scope.max = 150;
	// $scope.rangeValue = 150;
}])
