'use strict';
//dependent upon on Bootstrap

app.directive('activityDeviceSelect', function () {
  return {
    restrict: 'E',
    require: 'ngModel',
    replace: true,
    scope: {
      ngModel: '=',
      roomDevices: '=',
      powerInputMode: '=', //default: false (power off), true (power on, input)
      disable: '=' //if true, hides the list 
    },
    templateUrl: 'views/activity-device-select.html',
    link: function(scope, element, attrs) {
      scope.powerInputMode = scope.powerInputMode || false;
    }
  };
});

'use strict';

app.directive('addDelayStep', function ($modal, $timeout) {
  return {
    restrict: 'A',
    scope: {
      steps: '='
    },
    link: function(scope, element, attrs) {
      var modal = $modal({scope: scope, title: 'Set delay time', template: 'views/modal-tpls/add-delay.html', show: false});
      

      scope.addDelay = function (time) {
        scope.steps = scope.steps || [];
        scope.steps.push({name: 'Delay ' + time + ' seconds', type: 2, value: time*1000});
        // $timeout(function(){
        //   delete scope.delay;
        // }, 500);
      }; 

      element.on('click', function(event) {
        event.preventDefault();
        scope.delay = {};
        modal.$promise.then(modal.show);
      });

    }
  };
});
'use strict';

app.directive('addJumpTo', function ($modal, $timeout) {
  return {
    restrict: 'A',
    scope: {
      steps: '=',
      devices: '='
    },
    controller: function($scope, $element) {
      var modal = $modal({scope: $scope, title: 'Add a jump to a device', template: 'views/modal-tpls/add-jump-to.html', show: false});
      
      $scope.addJumpTo = function (device) {
        $scope.steps = $scope.steps || [];
        $scope.steps.push({'name': 'Jump to ' + device.name, 'type': 3, 'to': {'type': 1, 'value': device.id} });
      }; 

      $element.on('click', function(event) {
        event.preventDefault();
        $scope.jump = {};
        modal.$promise.then(modal.show);
      });
    }
  };
});
'use strict';

app.directive('addPage', function() {
  return {
    require: '^deviceInterface',
    restrict: 'E',
    scope: {
      
    },
    link: function(scope, element, attrs, interfaceCtrl) {
      element.on('click', function() {
        interfaceCtrl.addPage(scope);
      });
      
    },
    template: '<button type="button" class="btn btn-menu">Add a new page</button>'
  };
});
'use strict';

app.directive('deviceBtnDelete', function() {
  // Runs during compile
  return {
    restrict: 'E', // E = Element, A = Attribute, C = Class, M = Comment
    template: '<a title="Delete this button" ng-click="showModal()"><i class="fa fa-fw fa-lg fa-trash-o action-icon"></i></a>',
    scope: {
      selectedBtn: '='
    },
    replace: true,
    controller: function($scope, $modal) {
      var deleteModal = $modal({ scope: $scope, title: 'Delete this button', template:'views/modal-tpls/device-delete-btn.html', show:false});
      
      function showModal() {
        deleteModal.$promise.then(deleteModal.show);
      }
      function hideModal() {
        deleteModal.$promise.then(deleteModal.hide);
      }

      $scope.showModal = showModal;

      $scope.delete = function(obj) {

        var keys = ['id', 'page_btn_idx', 'name', 'device_id', 'room_id', 'repeat_min', 'repeat_macro', 'press_hold', 'repeatSetting'];

        for (var prop in obj) {
          if (keys.indexOf(prop) === -1) {
            delete obj[prop];
          } else {
            if (prop === 'repeatSetting') {
              obj[prop] = 'default';
            }
          }
        }
        $scope.selectedBtn = null;
        hideModal();
      };
    }  
  };
});
'use strict';

app.directive('deviceBtnEdit', function () {
  return {
    restrict: 'EA',
    replace: true,
    scope: {
      selectedBtn: '=',
      dbCon: '='
    },
    template: function(tElement, tAttrs) {
      var template;
      switch (tAttrs.content) {
        case 'add':
          template = '<button class="btn btn-menu" ng-click="showModal()">Add a button</button>';
          break;
        case 'edit':
        default:
          template = '<a title="Edit this button" ng-click="showModal()" ><i class="fa fa-fw fa-lg fa-pencil action-icon"></i></a>';
          break;
      }
      return template;
    },
    controller: function($scope, $element, $modal) {
      var editModal = $modal({ scope: $scope, title: 'Edit this button', template:'views/modal-tpls/device-edit-btn.html', show:false});
      
      function showModal() {
        $scope.newBtn = angular.copy($scope.selectedBtn);
        editModal.$promise.then(editModal.show);
      }
      function hideModal() {
        editModal.$promise.then(editModal.hide);
      }

      $scope.showModal = showModal;

      $scope.edit = function(oldValue, newValue) {
        console.log(oldValue);
        console.log(newValue);

        if (!newValue.hasOwnProperty('press_hold')) {
          newValue.press_hold = newValue.func.press_hold ? true:false;
        }

        if (!newValue.hasOwnProperty('image_name')) {
          newValue.image_name = '';
        }

        if (!newValue.hasOwnProperty('device_id')) {
          newValue.device_id = newValue.func.device_id;
        }

        if (!newValue.hasOwnProperty('room_id')) {
          newValue.room_id = newValue.func.room_id;
        }

        if (!newValue.hasOwnProperty('hidden_option')) {
          newValue.hidden_option = 0;
          newValue.activity = '';
          newValue.popup = 0;
        }
        
        _.assign(oldValue, newValue);

        hideModal();
      };
      
    }
  };
});
'use strict';

app.directive('deviceBtnMove', function() {
  return {
    restrict: 'E',
    replace: true,
    scope: {
      ngModel: '=',
      selectedBtn: '=',
      exists: '='
    },
    template: '<a title="Move button to another page" ng-click="showModal()"><i class="fa fa-fw fa-lg fa-exchange action-icon"></i></a>',
    controller: function($scope, $element, $modal) {
      var moveModal = $modal({ scope: $scope, title: 'Move button to another page', placement: 'top', template:'views/modal-tpls/device-move-btn.html', show:false});
      
      function showModal() {
        $scope.popupDialog = {};
        moveModal.$promise.then(moveModal.show);
      }
      function hideModal() {
        moveModal.$promise.then(moveModal.hide);
      }

      $scope.showModal = showModal;

      $scope.swapButtons = function(source, dest) {
        var temp1 = _.omit(source, ['id', 'page_btn_idx', 'name', 'device_id', 'room_id']),
            temp2 = _.omit(dest, ['id', 'page_btn_idx', 'name', 'device_id', 'room_id']);

        console.log(temp1);
        console.log(temp2);

        for (var prop1 in temp1) {
          dest[prop1] = temp1[prop1];
        }

        for (var prop2 in temp2) {
          source[prop2] = temp2[prop2];
        }

        hideModal();
      };
      
    }
  };
});
'use strict';
//dependent upon on Bootstrap

app.directive('deviceInterface', function () {
  return {
    restrict: 'E',
    scope: {
      ngModel: '=',
      popup: '=',
      exists: '=',
      hasPageBtn: '=',
      currentState: '='
    },
    templateUrl: 'views/device-interface.html',
    controller: function($scope, $modal, Devices) {
      console.log($scope.ngModel);

      $scope.ngModel.currentMenuPage = 1;
      $scope.ngModel.currentHardPage = 1;
      $scope.ngModel.selectedBtn = null;
      $scope.ngModel.repeatSetting = 'default';
      $scope.ngModel.activeTab = 'menu';
      //$scope.ngModel.newBtn = {};
      $scope.ngModel.menu = {
          pages: []
      };
      $scope.ngModel.hard = {
        pages: Devices.getHardBtnPages()
      };

      if ($scope.exists) { 
        $scope.ngModel.menu.pages = Devices.getMenuBtnPages();
      } else {
        if ($scope.popup) {
          // if popup copy its current state into the model  
          $scope.ngModel.menu.pages = $scope.currentState.menu.pages; 
        } else {
          // else initialize the device interface push a blank menu page
          $scope.ngModel.menu.pages.push(Devices.makeBlankMenuPage({room_id: $scope.ngModel.room.id, repeat: { min: 3, macro: 3}}));
        }
      }


      $scope.isEmpty = function(val) { return _.isEmpty(val); };
      $scope.sortableOptions = {
        stop: function( event, ui ) {
          var buttonId = _(buttonsArray).pluck('id').min().value();
          console.log(buttonId);
          for (var i = 0; i < buttonsArray.length; i++) {
            buttonsArray[i].page_btn_idx = i;
            //buttonsArray[i].id = buttonId;
            //buttonId++;
          }
          $scope.$apply();
        }
      };
      $scope.ngModel.deviceData = Devices.getCurrentData();

      $scope.ngModel.filteredMenuPage = $scope.ngModel.menu.pages[0];
      $scope.ngModel.filteredHardPage = $scope.ngModel.hard.pages[0];
      var buttonsArray = $scope.ngModel.menu.pages[0].btns;

      var menuPages = $scope.ngModel.menu.pages;
      var pageId = _(menuPages).pluck('id').max().value(),
          btnId = _(menuPages[menuPages.length - 1].btns).pluck('id').max().value()+1;

      console.log(pageId);
      console.log(btnId);



      $scope.addPage = function() {
        var btns = [];
        for (var i=0; i < 6; i++) {
          btns.push(Devices.makeBlankMenuButton(btnId, i, $scope.ngModel.deviceData));
          btnId++;
        }
        pageId++;
        console.log('pushing page with id of ' + pageId);
        $scope.ngModel.menu.pages.push({id: pageId, btns: btns});

      };

      $scope.menuPageChanged = function(page) {
        $scope.ngModel.filteredMenuPage = $scope.ngModel.menu.pages[page - 1];
        buttonsArray = $scope.ngModel.menu.pages[page - 1].btns;
        $scope.ngModel.selectedBtn = null;
        console.log(buttonsArray);
      };

      $scope.hardPageChanged = function(page) {
        $scope.ngModel.filteredHardPage = $scope.ngModel.hard.pages[page - 1];
        buttonsArray = $scope.ngModel.hard.pages[page - 1].btns;
        $scope.ngModel.selectedBtn = null;
        console.log(buttonsArray);
      };

    }
  };
});

'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.');
          });
      }

    }
  };
});

'use strict';
//dependent upon on Bootstrap

app.directive('goBack', function () {
  return {
    restrict: 'E',
    replace: true,
    scope: {
      state: '@',
      stateParams: '@'
    },
    template: '<button class="btn btn-primary" ng-click="goBack()"><i class="fa fa-caret-left"></i> Back</button>',
    controller: function($rootScope, $scope, $state) {
      $scope.goBack = function () {
        //if no state is provided the directive will check the rootScope for the previous state
        if (!$scope.state) {
          $state.go($rootScope.previousState.name, $rootScope.previousState.params);
        } else {
          $state.go($scope.state, $scope.stateParams);
        }
      };

    }
  };
});

'use strict';
//dependent upon on Bootstrap

app.directive('hardwareInfo', function() {
  return {
    restrict: 'E',
    replace: true,
    scope: {
      device: '='
    },
    template: '<a title="{{device.name}} Info" ng-click="showInfoModal()"><i class="fa fa-fw fa-info-circle"></i></a>',
    controller: function($scope, $templateCache, $state, $timeout, $modal, Systems) {
      
      var infoModal = $modal({ scope: $scope, 
                               title: $scope.device.name + ' Info', 
                               template: 'hardware-info.html', 
                               show: false });
      
      $scope.showInfoModal = function() {
        $scope.isLoading = true;
        $scope.isSuccess = false;
        $scope.isError = false;

        infoModal.$promise.then(infoModal.show);

        //$timeout(function() {
          Systems.searchHardware(false, $scope.device.type, {mac: $scope.device.mac})
          .then(function(data) {
            $scope.isLoading = false;
            $scope.isSuccess = true;
            console.log(data);
            $scope.searchedDevice = data.searchedDevices[0];
          })
          .catch(function(error) {
            $scope.isLoading = false;
            $scope.isError = true;
          });
          
        //}, 4000);
      };


    }
  };
});
'use strict';

app.directive('hcmDelete', function ($http, $templateCache, $state, $modal,  toastr, Systems, Rooms) {
  
  return {
    restrict: 'EA',
    replace: true,
    scope: {
      room: '=',
      bstation: '=',  
      remote: '=',
      device: '=',
      type: '@' //string 
    },

    link: function (scope, element, attrs) {
      var modal,
          type = scope.type.toLowerCase();

      switch (scope.type) {
        case 'room':
          modal = $modal({
            scope: scope,
            title: 'Delete this room',
            template: 'delete-room.html',
            container: '#job-overview',
            show: false
          });

          scope.selections = {
            room: angular.copy(scope.room)
          };
          break;
        case 'bstation':
          modal = $modal({
            scope: scope,
            title: 'Delete this controller',
            template: 'delete-bstation.html',
            container: '#job-overview',
            show: false
          });

          scope.selections = {
            room: angular.copy(scope.room),
            bstation: angular.copy(scope.bstation)
          };
          break;

        case 'remote':
          modal = $modal({
            scope: scope,
            title: 'Delete this remote',
            template: 'delete-remote.html',
            container: '#job-overview',
            show: false
          });

          scope.selections = {
            room: angular.copy(scope.room),
            remote: angular.copy(scope.remote)
          };

          break;
        case 'device':
          modal = $modal({
            scope: scope,
            title: 'Delete this device',
            template: 'delete-device.html',
            container: '#job-overview',
            show: false
          });

          scope.selections = {
            room: angular.copy(scope.room),
            device: angular.copy(scope.device)
          };
          break;
        
        case 'default':
          throw new Error('There was an error retrieving information. Please try again. If the error continues please log out and then log in again.');
      }


      element.on('click', function(event) {
        if (scope.type === 'bstation') {
          var assignedDevices = scope.room.devices.filter(function(device) {
            return device.target_addr === scope.bstation.mac;
          });

          var len = assignedDevices.length;
          if (len) {     
            for (var str='', i=0; i<len; i++) {
              str += '<li>' + assignedDevices[i].name + '</li>';
            }
            return $modal({
              title: 'Cannot delete this base station', 
              content: 'You cannot delete <strong class="text-primary">' + scope.bstation.name + '</strong> until you unassign the following devices connected to it. <ul class="margin-top-md">'+ str +'</ul>',
              html: true
            });
          }
        } 

        modal.$promise.then(modal.show);
      });



      scope.deleteRoom = function(room) {
        var currentSystem = Systems.getCurrentSystem();

        Rooms.delete(room.id)
        .then(function(data) {    
          var roomIndex = _.findIndex(currentSystem.rooms, { 'id': room.id });
          currentSystem.rooms.splice(roomIndex, 1);
          console.log(currentSystem);
          Systems.loadSystem(currentSystem);
          if (Systems.currentRoom.id === room.id) {
            Systems.currentRoom.id = null;
          }
          $state.transitionTo($state.current, null, { reload: true, inherit: true, notify: true  });
        })
        .catch(toastr.error);
      };
   

      scope.deleteBstation = function(room, bstation) {

        var currentSystem = Systems.getCurrentSystem();

        Rooms.baseStations('delete',room.id, {mac: bstation.mac})
          .then(function(data) {    
            var roomIndex = _.findIndex(currentSystem.rooms, { 'id': room.id });
            var bstationIndex = _.findIndex(currentSystem.rooms[roomIndex].bstations, { 'id': bstation.id });
            currentSystem.rooms[roomIndex].bstations.splice(bstationIndex, 1);
            console.log(currentSystem);
            Systems.loadSystem(currentSystem);
            $state.transitionTo($state.current, null, { reload: true, inherit: true, notify: true  });
          })
          .catch(toastr.error);
      };


      scope.deleteRemote = function(room, remote) {

        var currentSystem = Systems.getCurrentSystem();

        Rooms.delRemote(room.id, {mac: remote.mac})
          .then(function(data) {    
            var roomIndex = _.findIndex(currentSystem.rooms, { 'id': room.id });
            var remoteIndex = _.findIndex(currentSystem.rooms[roomIndex].remotes, { 'id': remote.id });
            currentSystem.rooms[roomIndex].remotes.splice(remoteIndex, 1);
            console.log(currentSystem);
            Systems.loadSystem(currentSystem);
            $state.transitionTo($state.current, null, { reload: true, inherit: true, notify: true  });
          })
          .catch(toastr.error);
      };


      scope.deleteDevice = function(room, device) {
        var currentSystem = Systems.getCurrentSystem();

        $http({
          method: 'POST',
          url: '/urcassistant/api/device/delete/' + room.id + '/' + device.id
        }).
        success(function(data) {
          if(data.result) {
            var roomIndex = _.findIndex(currentSystem.rooms, { 'id': room.id });
            var deviceIndex = _.findIndex(currentSystem.rooms[roomIndex].devices, { 'id': device.id });
            currentSystem.rooms[roomIndex].devices.splice(deviceIndex, 1);
            console.log(currentSystem);
            Systems.loadSystem(currentSystem);
            $state.transitionTo($state.current, null, { reload: true, inherit: true, notify: true  });
          }
          else {
            toastr.error(data.error);
          }
        }).
        error(toastr.error);
      };
    }
  };
});



  
  



  


  


  
  

  



'use strict';

app.directive('hcmEdit', function ($http, $templateCache, $state, $modal, toastr, Systems, Rooms) {
  
  return {
    restrict: 'EA',
    replace: true,
    scope: {
      system: '=',
      room: '=',
      bstation: '=',
      device: '=',
      type: '@' //takes in a String for edit type (i.e. system, room, device, bstation)
    },

    link: function (scope, element, attrs) {
      var modal, type = scope.type.toLowerCase();

      scope.lightLevels = [ {'value': 0, 'label': 'Off'}, {'value': 1, 'label': 'Low'}, {'value': 2, 'label': 'Medium'}, {'value': 3, 'label': 'High'}];

      switch (scope.type) {
        case 'system':
          modal = $modal({
            scope: scope,
            title: 'Edit this system',
            template: 'edit-system.html',
            container: '#job-overview',
            show: false
          });

          scope.selections = {
            system: angular.copy(scope.system)
          };
          break;
        case 'room':
          modal = $modal({
            scope: scope,
            title: 'Edit this room',
            template: 'edit-room.html',
            container: '#job-overview',
            show: false
          });

          scope.selections = {
            room: angular.copy(scope.room)
          };
          break;
        case 'device':
          modal = $modal({
            scope: scope,
            title: 'Edit this device',
            placement: 'top',
            template: 'edit-device.html',
            container: '#job-overview',
            show: false
          });

          scope.selections = {
            room: angular.copy(scope.room),
            device: angular.copy(scope.device)
          };
          scope.selections.device.ramp_start /= 1000;
          scope.selections.device.ramp_speed /= 1000;
          break;
        case 'bstation':
          modal = $modal({
            scope: scope,
            title: 'Edit this controller',
            template: 'edit-bstation.html',
            container: '#job-overview',
            show: false
          });

          scope.selections = {
            room: angular.copy(scope.room),
            bstation: angular.copy(scope.bstation)
          };
          break;
        case 'default':
          throw new Error('There was an error retrieving information. Please try again. If the error continues please log out and then log in again.');
      }

      scope.editSystem = function(system) {
        var currentSystem = Systems.getCurrentSystem();

        console.log('editSystem called');
        if (!_.isEqual(currentSystem, system)) {
          var jsonData = JSON.stringify( { name : system.name } );
          console.log(jsonData);
          Systems.editSystem(system.id, jsonData).
            then(function(data) {    
              currentSystem.name = system.name;
              Systems.loadSystem(currentSystem);
              $state.transitionTo($state.current, null, { reload: true, inherit: true, notify: true  });
            }).
            catch(toastr.error);
        }
      };

      scope.editRoom = function(room) {
        var currentSystem = Systems.getCurrentSystem();
        var roomIndex = _.findIndex(currentSystem.rooms, { 'id': room.id });
        var currentRoom = currentSystem.rooms[roomIndex];

        if (!_.isEqual(currentRoom, room)) {
          var jsonData = JSON.stringify( { name : room.name } );
          Rooms.edit(room.id, jsonData).
            then(function(data) {    
              currentRoom.name = room.name;
              Systems.loadSystem(currentSystem);
              $state.transitionTo($state.current, null, { reload: true, inherit: true, notify: true  });
            }).
            catch(toastr.error);
        }
      };


      scope.editBstation = function(room, bstation) {
        var currentSystem = Systems.getCurrentSystem(),
                roomIndex = _.findIndex(currentSystem.rooms, { 'id': room.id }),
              bstationIndex = _.findIndex(currentSystem.rooms[roomIndex].bstations, { 'id': bstation.id }),
            currentBstation = currentSystem.rooms[roomIndex].bstations[bstationIndex];

        if (!_.isEqual(currentBstation, bstation)) {
          var jsonData = JSON.stringify( { name : bstation.name, mac: bstation.mac, type: bstation.type, lightLevel: bstation.light_level } );
          Rooms.baseStations('edit', room.id, jsonData).
            then(function(data) {    
              currentBstation.name = bstation.name;
              currentBstation.light_level = bstation.light_level;
              Systems.loadSystem(currentSystem);
              $state.transitionTo($state.current, null, { reload: true, inherit: true, notify: true  });
            }).
            catch(toastr.error);
        }
      };



      scope.editDevice = function(room, device) {
        var currentSystem = Systems.getCurrentSystem(),
                roomIndex = _.findIndex(currentSystem.rooms, { 'id': room.id }),
              deviceIndex = _.findIndex(currentSystem.rooms[roomIndex].devices, { 'id': device.id }),
            currentDevice = currentSystem.rooms[roomIndex].devices[deviceIndex],
            clonedDevice = _.clone(device);

        clonedDevice.ramp_start *= 1000;
        clonedDevice.ramp_speed *= 1000;

        if (!_.isEqual(currentDevice, clonedDevice)) {
          var jsonData = JSON.stringify( {
            name : clonedDevice.name,
            targetType : clonedDevice.target_type,
            targetAddr : clonedDevice.target_addr,
            targetPort: clonedDevice.target_port,
            repeatMin: clonedDevice.repeat_min,
            repeatMacro: clonedDevice.repeat_macro,
            rampStart: clonedDevice.ramp_start,
            rampSpeed: clonedDevice.ramp_speed,
            autoCr: clonedDevice.auto_cr
          });

          $http({
            method: 'POST',
            url: '/urcassistant/api/device/edit/' + room.id + '/' + device.id,
            data : jsonData
          }).
          success(function(data) {
            if(data.result) {
              _.assign(currentDevice, clonedDevice);
              Systems.loadSystem(currentSystem);
              $state.transitionTo($state.current, null, { reload: true, inherit: true, notify: true  });
            }
            else {
              toastr.error(data.error);
            }
          }).
          error(toastr.error);
        }
      };

      element.on('click', function(event) {
        modal.$promise.then(modal.show);
      });




    }
  };
});



  

  

  



'use strict';
app.directive('nextAction', function(){
  return {
    restrict: 'AE',
    replace: true,
    templateUrl: 'views/add-macros/next-action.html',
    scope: {
      continueState: '@',
      backState: '@'
    },
    controller: function($scope, $state) {
      $scope.continue = function() {
        $state.go($scope.continueState);
      };
      $scope.backToRoom = function() {
        $state.go($scope.backState);
      };
      $scope.finish = function() {
        $state.go('menu.advanced.options');
      };
    }
  };
});
'use strict';

app.directive('refreshHardware', function() {
  return {
    restrict: 'EA',
    require: '^ngModel',
    scope: {
      reset: '=',
      ngModel: '=',
      deviceType: '='
    },
    template: '<button  class="btn btn-success" type="button" ng-click="refresh()"><i class="fa fa-refresh"></i>&nbsp;&nbsp;Refresh the list</button>',
    replace: true,
    controller: function($scope, toastr, Systems) {
      $scope.refresh = function() {

        //Reset previously selected choice to null
        $scope.reset = null;
        
        Systems.searchHardware(true, $scope.deviceType).then(
          function(data) {
            console.log('searchedDevices', data);
            $scope.ngModel = data.searchedDevices;
            $scope.$parent.searchKey = data.searchKey;
          },
          function (error) {
            if (error.match('NO DEVICE')) {

            } else {
              toastr.error(error);
            }
          }
        );
        
      };
    }
  };
});
'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);
    } 
  };
});

'use strict';
//dependent upon on Bootstrap

app.directive('selectRoom', function () {
  return {
    restrict: 'E',
    require: 'ngModel',
    replace: true,
    scope: {
      ngModel: '=',
      rooms: '=',
      disable: '='
    },
    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.room" ng-if="!disable" ng-value="room">' + 
                  '<input type="radio" name="room" ng-model="ngModel.room" ng-if="disable" ng-disabled="room.devices.length === 0" ng-value="room">' +
                  '<strong>{{room.name}}</strong>' +
                  '<p><small class="text-muted" ng-if="room.devices.length === 0">This room has no devices yet.</small></p>' +
                '</label>' +
              '</div></div>',
    link: function (scope, element, attrs, ngModelCtrl) {
      scope.$watch('ngModel.room.id',
        function(newValue, oldValue) {
          if (newValue) {
            ngModelCtrl.$setValidity('roomSelected', true);
          } else {
            ngModelCtrl.$setValidity('roomSelected', false);
          }
        });
    }
  };
});
'use strict';

app.directive('timeSettings', function() {
  return {
    restrict: 'EA',
    replace:true,
    scope: {
      system: '=',
      timeZones: '='
    },
    template: '<a ng-click="showTimeSettingsModal()">Change the time settings for this system </a>',
    //<small>{{system.timezone.data.name}}</small>
    controller: function($scope, $modal, toastr, Systems) {
      var timeSettingsModal = $modal({
        scope: $scope,
        template: 'views/modal-tpls/change-tz.html',
        show: false
      });


      $scope.setTimeZone = function() {
        console.log($scope.time.format);
        var data = JSON.stringify({ id: $scope.time.zone.data.id , dst: $scope.time.zone.dst ? 1:0, time_type: $scope.time.format === 'hh:mm:ss a' ? 0:1 });
        Systems.setTimeZone(data).then(function(data) {
          console.log(data);
          $scope.system.timezone.data = angular.copy($scope.time.zone.data);
          $scope.system.timezone.dst = $scope.time.zone.dst ? 1:0;
          $scope.system.time_type = $scope.time.format === 'hh:mm:ss a' ? 0:1;
          Systems.loadSystem($scope.system);
        }).catch(function(error) {
          toastr.error(error, 'Error');
        });
      };

      $scope.checkDST = function() {
        if ($scope.time.zone.data.s_time === '0.0.0 00:00:00' || !$scope.time.zone.data.d_bias) {
          $scope.time.zone.dst = false;
        } else {
          $scope.time.zone.dst = true;
        }
      };

      $scope.showTimeSettingsModal = function () {
        $scope.time = {};
        $scope.time.zone = { data: angular.copy($scope.system.timezone.data), dst: $scope.system.timezone.dst ? true:false };
        $scope.time.format = $scope.system.time_type === 0 ? 'hh:mm:ss a': 'HH:mm:ss';
        timeSettingsModal.$promise.then(timeSettingsModal.show);       
      };
    }
  };
});
'use strict';

app.directive('userPanel', function() {
  return {
    restrict: 'EA',
    //replace: true,
    scope: {},
    template: '<a class="btn btn-nav pull-right" ui-sref="home" ng-if="!currentUser">' +
                '<i class="fa fa-user fa-lg"></i>&nbsp;&nbsp;<span>Login &#47; Register</span>'+
              '</a>'+
              '<button class="btn btn-nav pull-right" ng-if="currentUser" data-placement="bottom-right" data-html="1" data-trigger="click" bs-dropdown="dropdown">'+
                '<i class="fa fa-user fa-lg"></i>&nbsp;&nbsp; {{currentUser.username}} &nbsp;<i class="fa fa-caret-down"></i>'+
              '</button>',
    controller: function($scope, $state, $window, $modal, Auth, User) {

      $scope.currentUser = null;

      $scope.logoutUser = function () {
        User.logout();
        $window.location.href = '/urcassistant';
      };

      $scope.$on('user:set', function(event, currentUser) {
        console.log('caught user:set event');
        $scope.currentUser = currentUser;
      });

      $scope.$on('user:unset', function(event) {
        console.log('caught user:unset event');
        $scope.currentUser = null;
      });


      $scope.dropdown = [
        {
          "text": "<i class=\"fa fa-list\"></i>&nbsp;&nbsp;New Job",
          "href": "/urcassistant#/home",
          "target": "_self"
        },
        {
          "text": "<i class=\"fa fa-users\"></i>&nbsp;&nbsp;Account Settings",
          "href": "/urcassistant#/account-settings",
          "target": "_self"
        },
        {
          "text": "<i class=\"fa fa-sign-out\"></i>&nbsp;&nbsp;Logout",
          "click": "logoutUser()"
        }
      ];


    }
  };
});
