(function () {
	'use strict';

	angular.module('uniflash').directive('ufTargetSetup', targetSetup);

	function targetSetup() {

		var directive = {
			restrict: 'E',
			templateUrl: 'target_setup/target_setup.html',
			controller: TargetSetupController,
			controllerAs: 'vm',
			scope: {}
		};

		return directive;
	}


	TargetSetupController.$inject = ['$q', '$state', 'ufTargetConfig', '$location', '$anchorScroll', '$sce', 'ticHighlightSrv', 'ufSession', 'ufPreferencesSrv'];

	function TargetSetupController($q, $state, ufTargetConfig: uniflash.target_config.TargetConfig, $location, $anchorScroll, $sce, ticHighlightSrv, ufSession, ufPreferencesSrv) {

		var vm = this;
		vm.ticHighlightSrv = ticHighlightSrv;

		vm.title = 'New Configuration - Choose your Device and Connection';
		vm.deviceFilter = '';
		vm.connectionFilter = '';
		vm.selectedDevice = '';
		vm.selectedConnection = '';

		vm.lpDisplayCtrl = 'Cell View';
		vm.lpTextFilter = '';
		vm.lpCategoryFilter = 'All';
		vm.deviceCategoryFilter = 'All';

		vm.showSavedConfig = true;
		vm.showLP = true;
		vm.showMainNewConfig = true;
		vm.showNewConfig = true;

		vm.files = [];
		vm.noFilesMessage = 'No Saved Sessions Available';

        var devices: uniflash.target_config.DeviceSetup[];

		ufPreferencesSrv.getRecentSessions()
			.then((files) => {
				vm.files = files;
			});

		ufTargetConfig.getLaunchPads().then(function (launchpads) {
			vm.launchpads = launchpads;
		});

		ufTargetConfig.getDevices()
			.then((newDevices: uniflash.target_config.DeviceSetup[]) => {
				devices = newDevices;
				filterDeviceList();
			});

		vm.selectedDeviceChanged = function () {
			if (vm.selectedDevice) {
                setConnections(vm.selectedDevice).then(function () {
                    vm.filterConnectionList();
                    vm.selectedConnection = vm.filteredConnectionList[0];
                });
            } else {
                vm.filteredConnectionList = [];
                vm.selectedConnection = '';
            }
		};

		vm.startClicked = function () {
			$state.go('main.Program', {
				deviceXMLFile: vm.selectedDevice.xmlFile,
				connectionXMLFile: vm.selectedConnection.xmlFile,
				params: { forceSessionInit: true }
			});
		};

		vm.selectDevice = function () {
			vm.selectedDeviceChanged();
		};

        vm.deviceFilterChanged = function () {
            filterDeviceList();

            vm.selectedDevice = vm.filteredDevices[0];
            vm.selectedDeviceChanged();
        };

		function filterDeviceList() {
			// filter the device list by category
			var categoryDeviceList = _.filter(devices, function (device) {
				if (!device.id) { return false; }	// weird case where the device ID is not available
				if (vm.deviceCategoryFilter === 'All') { return true; }
				else if (vm.deviceCategoryFilter === 'C2000') {
					return ((device.id.toLowerCase().indexOf('tms320f28') !== -1) ||
						(device.id.toLowerCase().indexOf('tms320c28') !== -1) ||
						(device.id.toLowerCase().indexOf('tms320r28') !== -1) ||
						(device.id.toLowerCase().indexOf('f28plc') !== -1) ||
						(device.id.toLowerCase().indexOf('f28m3') !== -1));
				} else if (vm.deviceCategoryFilter === 'MSP430') {
					return ((device.id.toLowerCase().indexOf('msp430') !== -1) ||
						(device.id.toLowerCase().indexOf('msp432') !== -1) ||
						(device.id.toLowerCase().indexOf('rf430') !== -1) ||
						(device.id.toLowerCase().indexOf('cc430') !== -1));
				} else if (vm.deviceCategoryFilter === 'Safety') {
					return false;
				} else if (vm.deviceCategoryFilter === 'Wireless') {
					return ((device.id.toLowerCase().indexOf('cc13') !== -1) ||
						(device.id.toLowerCase().indexOf('cc25') !== -1) ||
						(device.id.toLowerCase().indexOf('cm25') !== -1) ||
						(device.id.toLowerCase().indexOf('cc26') !== -1));
				} else if (vm.deviceCategoryFilter === 'Tiva') {
					return ((device.id.toLowerCase().indexOf('stellaris') !== -1) ||
						(device.id.toLowerCase().indexOf('tiva') !== -1));
				}

				return true;
            });

			// sort by name
			var orderedDeviceList = categoryDeviceList.sort(function (a: any, b: any) { return a.id.localeCompare(b.id); });

			// filter the device list by user search
            vm.filteredDevices = _.filter(orderedDeviceList, function (devices: any) {
                return devices.id.toLowerCase().indexOf(vm.deviceFilter.toLowerCase()) !== -1;
            });
		}

		vm.filterConnectionList = function () {
			// remove Data Snapshot and UART for now
			var removedEntriesConnectionList = _.filter(vm.selectedDevice.connections, function (connection: any) {
				return ((connection.id !== 'Data Snapshot Viewer') &&
					(connection.id !== 'UARTConnection'));
			});
			// sort by name
			var sortedConnectionList = removedEntriesConnectionList.sort(function (a: any, b: any) { return a.id.localeCompare(b.id); });
			// filter list with user filter string (case insenstive)
			vm.filteredConnectionList = _.filter(sortedConnectionList, function (connection: any) { return (connection.id.toLowerCase().indexOf(vm.connectionFilter.toLowerCase()) !== -1); });
		};

		function setConnections(device) {
			if (device) {
                return ufTargetConfig.getConnections(device.connectionIndices).then(function (connections) {
                    device.connections = connections;
                });
            } else {
                $q.resolve([]);
            }
		}

		vm.scrollTo = function (tag) {
			$location.hash(tag);
			$anchorScroll();
		};

		vm.configureLP = function (device, connection) {
			// clear the device and connection selection first before configuring a launchpad
			if (vm.deviceFilter !== '') {
				vm.deviceFilter = '';
			}
			if (vm.connectionFilter !== '') {
				vm.connectionFilter = '';
			}

			vm.selectedDevice = _.find(devices, function (curDevice: any) {
				return (curDevice.xmlFile.toLowerCase() === device.toLowerCase());
			});
			var promise = setConnections(vm.selectedDevice);
			promise.then(function () {
				vm.selectedConnection = _.find(vm.selectedDevice.connections, function (curConnection: any) {
					return (curConnection.xmlFile.toLowerCase() === connection.toLowerCase());
				});
				vm.startClicked();
			});
		};

		vm.getFilteredLPList = function () {
			return _.filter(vm.launchpads, function (lp: any) {
				var match1 = ((lp.name.toLowerCase().indexOf(vm.lpTextFilter.toLowerCase()) !== -1) ||
					(lp.device.toLowerCase().indexOf(vm.lpTextFilter.toLowerCase()) !== -1) ||
					(lp.connection.toLowerCase().indexOf(vm.lpTextFilter.toLowerCase()) !== -1));
				var match2 = ((vm.lpCategoryFilter === 'All') || (vm.lpCategoryFilter === lp.category));

				return (match1 && match2);
			});
		};

		vm.loadSession = function (selections) {
			ufSession.load(selections);
		};
	}

})();