'use strict';

app.directive('learnCommand', function () {
	return {
		restrict: 'EA',
		scope: {
			systemId: '=',
			model: '=',
			selectedBtn: '='
		},
		template: '<button type="button" class="btn btn-menu" ng-click="showLearnModal()">Learn!</button>',
		replace: true,
		controller: function($scope, $q, $timeout, $modal, Learning) {
			var learnModal = $modal({scope: $scope, backdrop: 'static', template: 'views/modal-tpls/learn-proc.html', show: false});
			var request;

			$scope.learnedData = null;

			function handleError(error) {
				console.log(error);
				//if (!error) { error='Learning process has been stopped.'}
				$scope.status = error ? '<span class="text-danger">' +  error + '</span>' : 'Learning process has been stopped.';
				$scope.retry = true;
				$scope.stop = false;
			}

			function makingRequest() {
				console.log('Called makingRequest');
				$scope.retry = false;
				$scope.stop = true;
				$scope.next = false;
				$scope.save = false;
				$scope.learnedData = null;
			}

			function learn() {
				console.log('Request being made: ', request);
				$scope.status = 'Attempting to start learning mode...';
							
				if ($scope.selectedBtnCopy.id < 8192 && !$scope.selectedBtnCopy.display_text) {
					$scope.selectedBtnCopy.display_text = angular.copy($scope.selectedBtnCopy.name);
					$scope.selectedBtnCopy.func = {};
					$scope.selectedBtnCopy.func.name = angular.copy($scope.selectedBtnCopy.name);
				}

				request = Learning.start($scope.systemId);
				makingRequest(); 
				
				request.promise.then(function(data) {
					$scope.status = '<span class="text-success">Ready to Learn.</span>';
					return $scope.systemId;
				})
				.then(function(id) {
					$scope.status = '<i class="fa fa-spinner"></i>&nbsp;&nbsp;Learning';
					request = Learning.attempt(id);
					return request.promise;
				})
				.then(function(data) {
					console.log(data);
					$scope.learnedData = data;
					$scope.status = '<span class="text-success">Successfully learned.</span>';
					$scope.next = true;
					$scope.save = true;
					$scope.retry = true;
					$scope.stop = false;
				})
				.catch(handleError);

			}


			function findAvailableId() {
				function filterLcdFuncs(id) {
					return id > 2048;
				}
				var db = $scope.model.deviceData.dbCon;
				var ids = _.pluck(db, 'id').filter(filterLcdFuncs); //ids is an empty array if no id is greater than 2048
				
				if (_.isEmpty(ids)) {
					return 2049;
				}

				ids = _.unique(ids).sort(function(a, b) {
					return a - b;
				});

				var min = _.min(ids) ;
				var counter = min;

				for (var i = 0; i < ids.length; i++) {
					if (ids[i] === counter) {
						counter++;
					} else {
						return counter;
					}
				}
				return counter;
			}

			function save() {
				_.assign($scope.selectedBtn, {display_text: $scope.selectedBtnCopy.display_text });

				var dbCommand = _.find($scope.model.deviceData.dbCon, {id: $scope.selectedBtnCopy.func.id });

				if (dbCommand){
					_.assign(dbCommand, { name: $scope.selectedBtnCopy.func.name, data: $scope.learnedData, type: 1 });
				} else {
					var func = { 
						id: $scope.selectedBtnCopy.id < 8192 ? $scope.selectedBtnCopy.id : findAvailableId(),
						name: $scope.selectedBtnCopy.func.name, 
						data: $scope.learnedData,
						type: 1,
						custom: 0,
						press_hold: 1,
						repeat_macro: $scope.model.deviceData.repeat.macro,
						repeat_min: $scope.model.deviceData.repeat.min,
						room_id: $scope.selectedBtnCopy.room_id,
						device_id: $scope.selectedBtnCopy.device_id
					};

					var btn = {
						image_name: '',
						press_hold: func.press_hold ? true:false,
						device_id: func.device_id,
						room_id: func.room_id,
						hidden_option: 0,
						activity: '',
						popup: 0,
						func: func
					};

					_.assign($scope.selectedBtn, btn);

					$scope.model.deviceData.dbCon.push(func);
				}
			}   

			function next() {
				var activeTab = $scope.model.activeTab;
				var pages = $scope.model[activeTab].pages;
				var btns = _.flatten(pages, 'btns');

				if (activeTab === 'menu') {   
					if ($scope.selectedBtn.page_btn_idx === 5) { 
						if ($scope.model.currentMenuPage !== pages.length) { 
							$scope.model.currentMenuPage++; 
							$scope.model.filteredMenuPage = $scope.model.menu.pages[$scope.model.currentMenuPage - 1];  
						} else { //if last menu page, go to hard btn pages
							$scope.model.activeTab = 'hard'; 
							$scope.model.currentHardPage = 1;             
							return next();
						}
					}
					$scope.selectedBtn =  _.find(btns, { 'id': $scope.selectedBtn.id+1 });
				} else {
					var index = _.findIndex(btns, $scope.selectedBtn);

					// if the currently selected hard btn is CH -, EXIT, or GREEN, it should move to the next page
					if ($scope.selectedBtn.id === 280 || $scope.selectedBtn.id === 307 || $scope.selectedBtn.id === 551 ) { 
						//if ($scope.model.currentPage !== pages.length) { 
						$scope.model.currentHardPage++; 
						$scope.model.filteredHardPage = $scope.model.hard.pages[$scope.model.currentHardPage - 1];         
					}

					$scope.selectedBtn = btns[index+1];
				}

				$scope.selectedBtnCopy = angular.copy($scope.selectedBtn);
			}

			$scope.showLearnModal = function() {
				$scope.stop = true;
				$scope.retry = false;
				$scope.next = false;
				$scope.save = false;

				$scope.selectedBtnCopy = angular.copy($scope.selectedBtn);
				learnModal.$promise.then(learnModal.show);
							
				learn();

			};

			$scope.changedBtnName = function() {
				//console.log($scope.learnCommandForm);
				//if ($scope.learnCommandForm.funcName.$pristine) {
					$scope.selectedBtnCopy.func.name = angular.copy($scope.selectedBtnCopy.display_text);
				//}
			};

			$scope.retryLearn = function() {
				$scope.status = 'Retrying...';
				learn();
			};

			$scope.saveLearn = function() {
				save();
				learnModal.hide();
			};

			$scope.stopLearn = function() {
				request.cancel('Learning process stopped');
				console.log('User cancelled request');
				learnModal.hide();
			};

			$scope.skipLearn = function() {
				request.cancel('Learning process stopped');
				console.log('User cancelled request');

				$timeout(function() {
					console.log('in timeout');
					next();
					learn();
					
				}, 500);
				
			};

			$scope.nextLearn = function() {
				save();
				next();
				learn();
			};
		}
	};
});