'use strict';
//dependent upon on Bootstrap

app.directive('selectDevice', function (){
  return {
    restrict: 'E',
    require: 'ngModel',
    replace: true,
    scope: {
      ngModel: '=',
      rooms: '='
    },
    template: '<div class="scrollable-window padding-left-sm">'+
              '<div class="radio" 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) {
      $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);
    } 
  };
});
