'use strict';
//dependent upon on Bootstrap

app.directive('selectDevice', function (){
	return {
		restrict: 'E',
		require: 'ngModel',
		replace: true,
		scope: {
			ngModel: '=',
			rooms: '=',
			room: '='
		},
		template: '<div class="scrollable-window padding-left-sm">'+
							'<div class="radio" ng-if="room.roomSelectVisible" ng-repeat="room in rooms track by room.id">' +
								'<label>' +
									'<input type="radio" name="room" ng-model="ngModel.roomId" ng-disabled="!room.devices.length" ng-click="ngModel.roomId !== room.id && clearSelection()" ng-value="room.id">' +
									'<strong>{{room.name}}</strong>' +
									'<small class="text-muted" ng-if="!room.devices.length">  This room has no devices yet.</small>' +
								'</label> ' +
								'<div class="fx-fade-down padding-left-md" ng-if="room.devices.length && ngModel.roomId === room.id">' +
									'<div class="radio" ng-repeat="device in room.devices track by device.id">' +
										'<label>' +
											'<input type="radio" name="device" ng-model="ngModel.deviceId"  ng-value="device.id">' +
											'<small class="text-muted">{{device.name}}</small>' +
										'</label>'+
									'</div>'+
								'</div>'+
							'</div></div>',
		controller: function($scope) {

			///dev_type이 twoway(1)인 device를 모두 제거.
			_.forEach($scope.rooms, function (room) {
				var item = null;
				while(item = _.where(room.devices, {'dev_type': 1})[0]) {
					var idx = room.devices.indexOf(item);
					room.devices.splice(idx, 1);
				} 
				//console.log('room.devices=', room.devices);
			});
			
			$scope.clearSelection = function() {
				$scope.ngModel.deviceId = null;
			};  
		},
		link: function(scope, element, attrs, ngModelCtrl) {

      scope.$watch('[ngModel.roomId, ngModel.deviceId]', function(newValue, oldValue) {        
				if (_.every(newValue)) {
					ngModelCtrl.$setValidity('deviceSelected', true);
				} else {
					ngModelCtrl.$setValidity('deviceSelected', false);
				}
			}, true);

      if (scope.room) {
        scope.ngModel.roomId = scope.room.id;

        _.forEach(scope.rooms, function(room) {
          if (room.id === scope.room.id) {
            room.roomSelectVisible = true;
          } else {
            room.roomSelectVisible = false;
          }
        });
      } else {
        _.forEach(scope.rooms, function(room) {
          room.roomSelectVisible = true;
        });
      }
		} 
	};
});
