(function () {
	'use strict';

	angular.module('uniflash').directive('ufDetectedDevices', ufDetectedDevices);

	function ufDetectedDevices() {

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

		return directive;
	}


	ufDetectedDevicesController.$inject = ['$state', '$rootScope', '$location', '$anchorScroll', 'ufTargetConfig', 'ufTargetSetupSrv', 'ticFileStorage', 'ufSettingsSrv', 'ufAddOnTargetSrv', 'ticAlerts', 'ufPreferencesSrv'];

	function ufDetectedDevicesController($state, $rootScope, $location, $anchorScroll, ufTargetConfig, ufTargetSetupSrv, ticFileStorage, ufSettingsSrv, ufAddOnTargetSrv, ticAlerts, ufPreferencesSrv) {
		var vm = this;
        vm.showDeviceDetection = true;
        vm.ufTargetSetupSrv = ufTargetSetupSrv;
		vm.ufSettingsSrv = ufSettingsSrv;
		vm.ufPreferencesSrv = ufPreferencesSrv;
        vm.errorMsg = '';
        
        ufTargetConfig.getLaunchPads().then(function (launchpads) {
            vm.launchpads = launchpads;
        });
        
        ufTargetConfig.getConnectionList().then(function (connectionList) {
            vm.connectionList = connectionList;
		});
        
        vm.isDeviceConfigurable = function(detectedDevice) {
            return ( ( detectedDevice.deviceName !== undefined ) &&
                     ( detectedDevice.deviceName.indexOf('Unable to determine') === -1 ) &&
                     ( detectedDevice.deviceName !== 'Not yet supported on this probe type') &&
                     ( detectedDevice.deviceName !== 'Unknown') &&
                     ( detectedDevice.deviceName.indexOf('unknown board') === -1) );
        };
        
        vm.configureDetectedDevice = function(detectedDevice, index) {
            if ( vm.isDeviceConfigurable(detectedDevice) ) {
                if ( detectedDevice.deviceXml.indexOf('CC3220') !== -1 ) {
					// image creator case
					if ( typeof ufAddOnTargetSrv.startIC === 'function' ) {
						ufAddOnTargetSrv.startIC();
					} else {
                        vm.ufTargetSetupSrv.setDetectDeviceStarted(0);
                        vm.errorMsg = 'CC3220 Image Creator is not support on Cloud. Please download the Desktop version.';
                    }
				} else {
					// all MSP430 device XMLs should have uppercase names now
					if ( detectedDevice.deviceXml.indexOf('msp430') !== -1 ) {
						detectedDevice.deviceXml = detectedDevice.deviceXml.toUpperCase();
					}
					ufTargetConfig.getConfigurables(detectedDevice.deviceXml,detectedDevice.connectionXml).then(function() {
					    // only works for XDS110
                        if ( detectedDevice.serial && (detectedDevice.connectionXml === 'TIXDS110_Connection') ) {
                            ufTargetConfig.setConfigurablesValue('SEPK.POD_PORT','Select by serial number');
                            ufTargetConfig.setConfigurablesValue('SEPK.POD_PORT_Select by serial number_SEPK.POD_SERIAL',detectedDevice.serial);
						}
					    $state.go('main.Program', {
							deviceXMLFile: detectedDevice.deviceXml,
							connectionXMLFile: detectedDevice.connectionXml,
							coreName: null,
                            forceSessionInit: true,
                            lp: true
                        }).then(function () {
                            vm.ufTargetSetupSrv.setDetectDeviceStarted(0);
                            vm.ufTargetSetupSrv.resetDetectedDeviceList();
                        });
					});
                }
            } else {
                // select the connection based on the xmlFile
                ufTargetConfig.getConnectionWithXML(detectedDevice.connectionXml).then(function (connection) {
                    ufTargetSetupSrv.selectedConnection = connection;
                    ufTargetSetupSrv.selectedDevice = '';
                    ufTargetSetupSrv.deviceSelected = false;
                    ufTargetSetupSrv.lpSelected = false;
                    ufTargetSetupSrv.hideDeviceSelectionOptions = false;
                    ufTargetConfig.getConnectionIndex(connection).then(function(index) {
                        ufTargetSetupSrv.setConnectionIndex = index;
                        $rootScope.$emit('UpdateDeviceList');
                    });
                    
                    vm.showDeviceDetection = false;
                    vm.ufTargetSetupSrv.setDetectDeviceStarted(0);
                    $location.hash('newConfig');
                    $anchorScroll();
                });
            }
        };
        
        vm.matchDetectedLP = function(detectedDevice) {
            return _.find(vm.launchpads, function(lp:any) {
                // special case for mmWave devices, where the connection does not have to match 
                let matched = ( (detectedDevice.deviceXml && lp.device.toLowerCase() === detectedDevice.deviceXml.toLowerCase()) && 
                                ( (lp.connection === detectedDevice.connectionXml) || 
                                  (detectedDevice.deviceXml.toLowerCase().indexOf('awr') !== -1) || 
                                  (detectedDevice.deviceXml.toLowerCase().indexOf('iwr') !== -1) ) );
                if ( matched ) {
                    detectedDevice.connectionXml = lp.connection;   // override the detected connection (mmWave devices will detect XDS110, but we want to default to using serial)
                }
                return matched;
            });
        };
        
        vm.translateConnectionName = function(connectionXml) {
            var matchedConnection = _.find(vm.connectionList, function(connection:any) {
                return connection.xmlFile === connectionXml;
            });
            return matchedConnection.id;  
        };
        
        // only support up to 3 MSP USB
        vm.msp430Connection = function(connectionXml:string) {
            return (connectionXml === "TIMSP430-USB") ||
                   (connectionXml === "TIMSP430-USB2") ||
                   (connectionXml === "TIMSP430-USB3");
        };

        vm.intrusiveDetectionCallback = function(result, index) {
            vm.ufTargetSetupSrv.setDetectDeviceStarted(0);
            let identifiedDevice = vm.ufTargetSetupSrv.getIdentifiedDeviceList();
            identifiedDevice[index] = result.name;
        };

        vm.startDetectionFromIntroPage = function() {
            vm.startDetecting=true;
            vm.ufPreferencesSrv.set('showDetectWelcomePage',false);
            vm.ufTargetSetupSrv.setDetectingStatus(true);
            vm.ufTargetSetupSrv.startDetection();
        };
        
        vm.getDownloadPercentStyle = function() {
            return {
                'width' : vm.ufTargetSetupSrv.detectDownloadPercentStatus().toString() + '%'
            }
        };
        
        vm.getDetectButtonClass = function() {
            let classes = "btn btn-sm btn-primary";
            if ( vm.ufTargetSetupSrv.getDetectingStatus() ) { classes += " disabled"; }

            return classes;
        };

        if ( vm.ufSettingsSrv.autoTargetDetectionSelectValue === 'Auto' ) {
            vm.ufTargetSetupSrv.startDetection();
        }
	}

})();