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



  
  



  


  


  
  

  


