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




    }
  };
});



  

  

  


