'use strict';
//dependent upon on Bootstrap

app.directive('functionSelect', function() {
  return {
    restrict: 'E',
    replace: true,
    scope: {
      systemId: '=',
      room: '=',
      device: '='
    },
    templateUrl: 'views/function-select.html',
    controller: function($scope, Systems, Devices) {
      $scope.fs = { functions: [] };
      var device = Systems.getDevice($scope.room.id, $scope.device.device_id);
      var funcs = Devices.getFunctions($scope.device.device_id);
      
      function getCommandId(type, device, data) {
        var command;
        switch(type) {
          case 0:               
            command = _.where(data, {'id': device.meta_pwr_off})[0];
            break;
          case 1:
            command = _.where(data, {'id': device.meta_pwr_on})[0];
            break;
          case 2:
            command = _.where(data, {'id': device.meta_in_toggle})[0];
            break;
          default:
            break;
        }
        return command;
      }


      if(funcs) {
        console.log('func load');
        var f = $scope.device.func;
        var funcData = _.where(funcs, {'id': _.isObject(f) ? f.id: f })[0];

        if (funcData) {
          $scope.device.func = funcData;
        } else {
          console.log('device func not set');    
          $scope.device.func = getCommandId($scope.device.type, device, funcs);
        }

        $scope.fs.functions = funcs;

      } else {
        Devices.fetchFunctions($scope.room.id, $scope.device.device_id).
          then(function(data) {
            
            Devices.setFunctions($scope.device.device_id, data);
            var funcData = _.where(data, {'id': $scope.device.func})[0];

            if (funcData) {
              $scope.device.func = funcData;
            } else {
              console.log('device func not set');    
              $scope.device.func = getCommandId($scope.device.type, device, data);
            }
  
            $scope.fs.functions = data;        
          }).
          catch(function() {
            alert('Unable to retrieve connected data Please try again.');
          });
      }

    }
  };
});
