'use strict';

app.directive('deviceSettingsForm', function (){
  return {
    restrict: 'EA',
    require: 'ngModel',
    replace: true,
    scope: {
      device: '=ngModel',
      info: '=',
      room: '=',
      formName: '='
    },
    templateUrl: 'views/installer/new/devices/settings.html',
    controller: function ($scope) {


      $scope.$watch('info', function(newValue, oldValue) {
        var deviceInfo = $scope.info;
        console.log(deviceInfo);
        if (deviceInfo) {
          if ($scope.device.db.source === 'DB') {
            $scope.device.target.port = deviceInfo.codeset === 'ip'? parseInt(deviceInfo.port, 10) : 255;
          } else {
            $scope.device.target.port = $scope.device.target.type === 'IP' ? null:255;
          }
        } else {
          $scope.device.target.port = $scope.device.target.type === 'IP' ? null:255;
        }
      });


      $scope.$watch('device.target', function(newValue, oldValue) {
        $scope.device.target.addr = '0';
      });

      $scope.$watch('device.target.type', function(newValue, oldValue) {
        if (newValue == 1) {
          $scope.device.target.addr = '0';
        } else {
          delete $scope.device.target.addr;
        }
      });
                                      
      
      // $scope.device.target.addr = $scope.device.target.addr || $scope.selection.room.bstations[0].id;

      $scope.$watch('device.db.source', function(newValue, oldValue) {
        $scope.info = null;
      });

     
    }
  };
});
