'use strict';


app.controller('EditMacroRoomController', function ($scope, $state, toastr, Systems) {
  $scope.system = Systems.getCurrentSystem();


  $scope.doNext = function() {
    return Systems.updateRoomDevices($scope.addMacro.room.id)
    .then(function(data) {
      var roomDevices = Systems.getRoomDevices();
      $scope.addMacro.room.devices = roomDevices.devices;
      $state.go('menu.advanced.edit-macros.macro-simulator', {roomId: $scope.addMacro.room.id});
    })
    .catch(toastr.error);
  };
});

app.controller('MacroSimulatorController', function ($scope, $state, $modal, toastr, Systems) {

  $scope.editMacro.currentPage = 1;

  //$scope.addMacro.room.devices = devices;

  function updateMainDevice() {
    Systems.updateMainDevice($scope.addMacro.room.id).then(function(data) {
      console.log(data);
      $scope.editMacro.mainDevice = data;
      $scope.client.page = angular.copy($scope.editMacro.mainDevice.pages[$scope.editMacro.currentPage - 1]);
      var numPages = $scope.editMacro.mainDevice.pages.length;
      $scope.editMacro.totalItems = numPages * 6;
    })
    .catch(toastr.error);
    
    updatePowerMacro();
  }
  
  updateMainDevice();

  function isJsonString(str) {
    try {
      JSON.parse(str);
    } catch (e) {
      return false;
    }
    return true;
  }

  $scope.isJsonString = isJsonString;

  $scope.editPowerMacro = function() {
    $scope.macroType.id = 0;

    var roomId = $scope.addMacro.room.id;
    Systems.updateCurrentMacroForPower(roomId).then( function(data) {
      console.log(data);
      $scope.addMacro.steps = cleanUp('macro', roomId, data.macro);
      //$scope.addMacro.autoWait = data.auto_wait ? true:false;
      $scope.addMacro.doneScreen.devices = cleanUp('activity', roomId, data.activity);
      $scope.addMacro.disablePopup = data.popup ? false:true;
      $state.go('menu.advanced.edit-macros.finish');
    }).catch(function (error) {
      alert(error);
    });
  };

  function cleanUp(type, roomId, arr) {
    console.log(arr);
    var filteredSteps = [];
    var steps =  isJsonString(arr) ? JSON.parse(arr):arr ;
    _.forEach(steps, function (step) {
      var device;

      if (type === 'macro') {
        if (step.type === 1) {
          device = Systems.getDevice(roomId, step.device_id);
          if (device) {
            step.name = device.name + ': ' + _.find(device.funcs, {'id': step.func}).name;
            filteredSteps.push(step);
          }
        } else if (step.type === 2) {
          step.name = 'Delay ' + step.value/1000 + ' seconds';
          filteredSteps.push(step);
        } else if (step.type === 3 && step.to.type === 1) {
            device = Systems.getDevice(roomId, step.to.value);
            if (device) {
              step.name = 'Jump to ' + device.name;
              filteredSteps.push(step);
            }
        }
      } else {
        device = Systems.getDevice(roomId, step.device_id);
        if (device) {
          step.name = device.name;
          step.funcs = device.funcs;
          filteredSteps.push(step);
        }

      }
    });
    return filteredSteps;
  }



  $scope.editBtnMacro = function(btn) {
    console.log(btn);
    var roomId = angular.copy($scope.addMacro.room.id);
    var activity =  btn.activity ? JSON.parse(btn.activity):[];

    $scope.addMacro.steps = cleanUp('macro', roomId, btn.macro);
    //$scope.addMacro.autoWait = btn.auto_wait ? true:false;
    $scope.addMacro.doneScreen.devices = cleanUp('activity', roomId, activity);
    $scope.addMacro.disablePopup = btn.popup ? false:true;
    $scope.addMacro.linkId = btn.link_id;
    $scope.addMacro.btnId = btn.id;

  
    $scope.macroType.id = btn.link_id !== -1? 1:2;
    
    switch ($scope.macroType.id) {
      case 1:
        $scope.addMacro.currentDevice = _.find($scope.addMacro.room.devices, {'id': btn.link_id});
        break;
      case 2:
        $scope.addMacro.button.name = btn.display_text;
        break;
      default:
        break;
    }
    $state.go('menu.advanced.edit-macros.finish');
  };

  $scope.pageChanged = function(page) {
    $scope.client.page = angular.copy($scope.editMacro.mainDevice.pages[page - 1]);
  };
  
  function updatePowerMacro() {
    Systems.updateCurrentMacroForPower($scope.addMacro.room.id).then( function(data) {
      $scope.powerMacro = data.macro;
    }).catch(function (error) {
      toastr.error(error);
    });
  }
  
  $scope.deleteMacro = function(mode, linkId, roomId, deviceId, btnId) {
    var handleSuccess = function(response) {
      if(response.data.result === true) {
        toastr.success('Automated Activity has been deleted');
        updateMainDevice();
      } else {
        toastr.error('Delete failed to work. Please try again.');
      }
    };

    var handleError = function(error){
      toastr.error(error, 'Error');
    };
    
    if (mode === 'power') {
      Systems.deletePowerMacro($scope.addMacro.room.id).then(handleSuccess, handleError);
    } else if (mode === 'device-btn') {
      if (linkId == '-1') {
        Systems.deleteButtonMacro(roomId, deviceId, btnId).then(handleSuccess, handleError);
      } else {
        Systems.deleteButtonMacroWithDevice(roomId, linkId).then(handleSuccess, handleError);
      }
    }
  };
  
  $scope.deleteMacroModal = function(mode, linkId, roomId, deviceId, btnId) {
    var scope = $scope.$new();
    scope.data = {
      mode: mode,
      linkId: linkId,
      roomId: roomId,
      deviceId: deviceId,
      btnId: btnId
    };
    
    var modal = $modal({
      scope: scope,
      template: 'views/modal-tpls/delete-macro.html',
      container: 'body',
      show: false
    });
    modal.$promise.then(modal.show);
  };

});

app.controller('EditMacroController', function ($scope, $timeout, $state, Systems) {

  $scope.addStep = function (device, func) {
    return {'name': device.name + ': ' + func.name, 'type': 1, 'device_id': device.id, 'func': func.id };
  };

  $scope.deleteAll = function() {
    var arr = $scope.addMacro.steps;
    while(arr.length > 0) {
      arr.pop();                     
    }
  };

  $scope.goBack = function() {
    $state.go('menu.advanced.edit-macros.macro-simulator', {roomId: $scope.addMacro.room.id});
  };

  $scope.doNext = function() {
    $state.go('menu.advanced.edit-macros.macro-done');
  };

});

app.controller('EditMacroDoneController', function ($scope, $state, toastr, Systems) {
  $scope.addMacro.doneScreen.index = 0;

  $scope.goBack = function() {
    $state.go('menu.advanced.edit-macros.finish');
  };

  $scope.doNext = function() {
    if ($scope.addMacro.disablePopup) {
      var steps =  angular.copy($scope.addMacro.steps);
      for (var i=0,  tot=steps.length; i < tot; i++) { delete steps[i].name; }
      //var autoWait = $scope.addMacro.autoWait ? 1:0;
      var jsonData = JSON.stringify( { auto_wait: 1 , edit_type: 1, popup: 0, activity: [], macro: steps } );

      var handleSuccess = function(response) {
        if(response.data.result === true) {
          $state.go('menu.advanced.edit-macros.next-action');
        } else {
          toastr.error('Your edit/create action failed.  Please try again.');
        }
      };

      var handleError = function(error){
        toastr.error("Please try again");
      };

      if ($scope.macroType.id === 0) {
        Systems.storePowerMacro($scope.addMacro.room.id, jsonData).then(handleSuccess, handleError);
      } else if ($scope.macroType.id === 1) {
        Systems.storeDeviceButtonMacro($scope.addMacro.room.id, $scope.addMacro.linkId, jsonData).then(handleSuccess, handleError);
      } else {
        Systems.storeCustomButtonMacro($scope.addMacro.room.id, $scope.addMacro.room.main_device_id, $scope.addMacro.btnId, jsonData).then(handleSuccess, handleError);
      }
    } else {
      $state.go('menu.advanced.edit-macros.macro-commands');
    }
  };

});


app.controller('EditMacroCommandsController', function ($scope, $state, toastr, Systems) {

  $scope.goBack = function() {
    if ($scope.addMacro.doneScreen.index === 0) {
      $state.go('menu.advanced.edit-macros.macro-done' );
    } else {
      $scope.addMacro.doneScreen.index--;
    }
  };

  $scope.doNext = function() {
    var len = $scope.addMacro.doneScreen.devices.length;
    if ($scope.addMacro.doneScreen.index + 1 === len) {
      //var autoWait = $scope.addMacro.autoWait ? 1:0;
      var steps =  angular.copy($scope.addMacro.steps);
      var activityData = angular.copy($scope.addMacro.doneScreen.devices);

      _.forEach(steps, function(step) { delete step.name; });
      _.forEach(activityData, function(activity) {
        activity.func = activity.func.id;
        delete activity.name;
        delete activity.repeat_min;
        delete activity.repeat_macro;
        delete activity.target_type;
        delete activity.target_addr;
        delete activity.target_port;
        delete activity.funcs;
      });

      var jsonData = JSON.stringify( { auto_wait: 1 , edit_type: 1, popup: 1, activity: activityData, macro: steps } );

      var handleSuccess = function(response) {
        if(response.data.result === true) {
          $state.go('menu.advanced.edit-macros.next-action');
        } else {
          toastr.error('Your edit/create action failed.  Please try again.');
        }
      };

      var handleError = function(error){
        toastr.error('Please try again');
      };

      if ($scope.macroType.id === 0) {
        Systems.storePowerMacro($scope.addMacro.room.id, jsonData).then(handleSuccess, handleError);
      } else if ($scope.macroType.id === 1) {
        Systems.storeDeviceButtonMacro($scope.addMacro.room.id, $scope.addMacro.linkId, jsonData).then(handleSuccess, handleError);
      } else {
        Systems.storeCustomButtonMacro($scope.addMacro.room.id, $scope.addMacro.room.main_device_id, $scope.addMacro.btnId, jsonData).then(handleSuccess, handleError);
      }
    } else {
      $scope.addMacro.doneScreen.index++;
    }

  };
});
