'use strict';

app.controller('ChangePasswordController', function ($scope, $state, toastr, User) {
  $scope.save = function () {

    var oldPassData = $scope.formData.currentPassword;
    var newPassData = $scope.formData.newPassword;
    var jsonData = JSON.stringify( { old_password : oldPassData, new_password : newPassData });
    
    User.changePassword(jsonData).then(function (data) {
      toastr.success('Successfully changed password!');
      $state.transitionTo('account-settings.main', null, { reload: true, inherit: true, notify: true  });     
    }).
    catch(function (error) {
      toastr.error(error);
    });
  };
});



'use strict';

app.controller('ActivitiesController', function($scope, Devices) {
  $scope.simpleActivity = { 'currentDevice': null, 'devices': [] };
  $scope.simpleActivity.index = 0;

  Devices.initFunctions();

});

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

  $scope.doNext = function() {

    Systems.updateCurrentMacroForDevice($scope.room.id, $scope.simpleActivity.currentDevice.id).then(
      function(data) {
        console.log(data);
        $state.go('menu.programming.activities.devices-to-use');
      },
      function (error) {
        alert(error);
      }
    );
  };
});


app.controller('ActivityDevicesController', function ($scope, $state, Systems, Devices) {
  var dataActivity = Systems.getCurrentMacro();
  $scope.simpleActivity.devices = [];
  console.log(dataActivity);


  if(dataActivity && dataActivity.edit_type === 0 && dataActivity.activity.length ) {//simple activity
    _.forEach(dataActivity.activity, function(data) {
      var device = Systems.getDevice($scope.room.id, data.device_id);

      if (device) {
        $scope.simpleActivity.devices.push({
          'device_id': data.device_id,
          'name': device.name,
          'type': data.type,
          'func': data.func,
          'repeat_min': device.repeat_min,
          'repeat_macro': device.repeat_macro,
          'target_type': device.target_type,
          'target_addr': device.target_addr,
          'target_port': device.target_port
        });
      }
    });
  }
  else {
    _.forEach($scope.room.devices, function(device) {
      if ($scope.simpleActivity.currentDevice.id === device.id && _.isEmpty($scope.simpleActivity.devices)) {
        $scope.simpleActivity.devices.push({
          'device_id': device.id,
          'name': device.name,
          'type': 1,
          'func': null,
          'repeat_min': device.repeat_min,
          'repeat_macro': device.repeat_macro,
          'target_type': device.target_type,
          'target_addr': device.target_addr,
          'target_port': device.target_port
        });
      }
    });
  }

  $scope.goBack = function() {
    $scope.simpleActivity.devices = [];
    Devices.initFunctions();
    $state.go('menu.programming.activities.choose-device' );
  };

  $scope.doNext = function() {
    $state.go('menu.programming.activities.commands');
  };

});

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

  $scope.goBack = function() {
    if ($scope.simpleActivity.index === 0) {
      $state.go('menu.programming.activities.devices-to-use');
    } else {
      $scope.simpleActivity.index--;
    }
  };

  $scope.incrIdx = function() { $scope.simpleActivity.index++; };


  $scope.finish = function() {
    //Save to server
    var sendData = angular.copy($scope.simpleActivity.devices);

    for (var i=0,  tot=sendData.length; i < tot; i++) {
      sendData[i].func = sendData[i].func.id;
      delete sendData[i].name;
      delete sendData[i].repeat_min;
      delete sendData[i].repeat_macro;
      delete sendData[i].target_type;
      delete sendData[i].target_addr;
      delete sendData[i].target_port;
    }

    var jsonData = JSON.stringify( { auto_wait : 1, edit_type : 0, popup : 1, activity : sendData, macro : []} );
    console.log(jsonData);

    Systems.storeDeviceButtonMacro($scope.room.id, $scope.simpleActivity.currentDevice.id, jsonData).then(function(response) {
      if(response.data.result === true) {
        $state.go('menu.programming.options');
      }
      else {
        alert('Your edit/create action failed.  Please try again.');
      }
    }, function(error){
      alert("Please try again");
    });

  };

});

'use strict';

app.controller('SelectBaseController', function ($scope, $state, toastr, availableModels, Systems, Rooms) {
  $scope.bs = {
    name: '',
    modelType: availableModels[0]
  };

  $scope.availableModels = availableModels;

  $scope.finish = function () {
    var currentSystem = Systems.getCurrentSystem(),
             jsonData = JSON.stringify({ type : $scope.bs.modelType, name: $scope.bs.name, lightLevel: 2 });

    
    var addBStation = function(roomId, json) {
      return Rooms.baseStations('add', roomId, json).then(function(data) { 
        toastr.success('Successfully added ' + $scope.bs.name + '.');
        return currentSystem.id;
      });
    };

    var updateSystem = function(id) {
      return Systems.updateSystem(id).then(function (data) {
        console.log(data);
        return $state.transitionTo('menu.programming.options', {}, { reload: true, inherit: true, notify: true  });
        //$state.go('menu.programming.option');
      });
    };

    addBStation($scope.room.id, jsonData)
      .then(updateSystem)
      .catch(function(error) {
        toastr.error(error, 'Error');
      });

  };
});
'use strict';
/**
 * @ngdoc controller
 * @name DeviceTypeController
 * @description
 *  device type 선택
 */
app.controller('DeviceTypeController', function ($scope, $state, categories) {
  if (!$scope.device.type) {
    $scope.device.type = {id: categories[0].id, name: categories[0].name, device: categories[0].device};  // 기본값 설정
  }
  $scope.types = categories;

  $scope.doNext = function () {
    $state.go('menu.programming.add-device.device-name');
  };
});

/**
 * @ngdoc controller
 * @name DeviceNameController
 * @description
 *  device name 입력
 */
app.controller('DeviceNameController', function ($scope, $state, $modal, toastr, Database, Rooms) {
  $scope.device.name = angular.copy($scope.device.type.device);

  var getDeviceBrands = function() {
    Database.retrieveDeviceBrands($scope.device.type.name).then(function(data) {
      $state.go('menu.programming.add-device.device-brand');
    }).catch(toastr.error);
  };

  $scope.getBrandsFromDB = getDeviceBrands;

  // 같은 이름의 device name 이 이미 등록되어 있음을 알리는 modal
  var modal = $modal({
    scope: $scope,
    title: 'Duplicate device name',
    container: '.editor-container',
    template: 'views/modal-tpls/duplicate-name.html',
    show: false
  });

  $scope.doNext = function() {
    var deviceNames = _.pluck(Rooms.getDevices($scope.room.id), 'name');
    if (_.contains(deviceNames, $scope.device.name)) {
      modal.$promise.then(modal.show);
    } else {
      getDeviceBrands();
    }
  };
});

/**
 * @ngdoc controller
 * @name DeviceBrandController
 * @description
 *  device brand 선택
 */
app.controller('DeviceBrandController', function ($scope, $state, Database, Devices) {
  $scope.device.brand = null;
  $scope.brands = Database.getBrands();

  $scope.doNext = function () {
    Devices.setCurrentDevice(angular.copy($scope.device));

    $state.go('menu.programming.add-device.device-model');
  };
});

/**
 * @ngdoc controller
 * @name DeviceModelController
 * @description
 *  device popuplar model 선택
 */
app.controller('DeviceModelController', function ($scope, $state, $modal, $http, toastr, popularDevices, Database) {

  $scope.device.model = null;
  $scope.device.info = null;
  $scope.query.value = '';

  $scope.models = popularDevices;
  $scope.models.ir = [];
  $scope.models.ip = [];

  _.forEach(popularDevices.p_ir, function(device, i) {
    device.index = i;
    $scope.models.ir.push(device);
  });

  _.forEach(popularDevices.p_ip, function(device, i) {
    device.index = i;
    $scope.models.ip.push(device);
  });

  if ($scope.models.ir.length) {
    $scope.device.targetType = 1;
  }

  $scope.doNext = function () {
    return Database.getDeviceInfo($scope.device.type.name, $scope.device.brand.name, $scope.device.model.id, $scope.device.targetType, $scope.device.model.type)
      .then(function(data) {
        var attrs = data.attr;
        console.log(attrs);
        if (attrs.codeset === 'ip') {
          $scope.device.targetPort = $scope.device.targetPort || parseInt(attrs.port, 10);
        } else {
          $scope.device.targetPort = 255;
          $scope.device.targetAddr = $scope.room.bstations[0].mac;
        }

        $scope.device.powerOff = false;
        if (data.meta.length) {
          _.each(data.meta, function(meta) {
            if (meta.strid === 'POWER_OFF' || meta.strid === 'POWER_TOGGLE') {
              $scope.device.powerOff = true;
            }
          });
        }

        $state.go('menu.programming.add-device.device-settings');
      })
      .catch(toastr.error);
  };

  // 테스트 팝업 화면 띄우기
  $scope.showTestModal = function() {

    // power on, mute, 나머지 commands 얻기 위해 getDeviceInfo
    Database.getDeviceInfo($scope.device.type.name, $scope.device.brand.name, $scope.device.model.id, $scope.device.targetType, $scope.device.model.type)
      .then(function(data) {
        $scope.device.info = data;
        $scope.device.powerBtn = false;
        $scope.device.powerBtnData = null;
        $scope.device.muteBtn = false;
        $scope.device.muteBtnData = null;

        _.each(data.btns, function(btn) {
          if (btn.def == 'POWER ON' || btn.def == 'POWER TOGGLE') {
            $scope.device.powerBtn = true;
            $scope.device.powerBtnData = btn.cmd;
          }
          if (btn.def == 'MUTE') {
            $scope.device.muteBtn = true;
            $scope.device.muteBtnData = btn.cmd;
          }
        });

        if (data.attr.codeset === 'ip') {
          $scope.device.targetPort = parseInt(data.attr.port, 10);
        } else {
          $scope.device.targetPort = -1;
        }

        var modal = $modal({
          scope: $scope,
          placement: 'top',
          template: 'views/modal-tpls/test-commands.html',
          container: 'body',
          show: false
        });
        modal.$promise.then(modal.show);
      })
      .catch(toastr.error);
  };

  $scope.device.testBstationMac = $scope.room.bstations[0].mac;

  // 테스트 실행
  $scope.btnTest = function(func) {
    var testData = {},
      data;

    if($scope.device.targetType === 2) {
      if (!$scope.device.targetAddr) {
        toastr.error('An IP address is required.');
        return;
      }
    }

    // power on
    if (func == 'power') {
      data = $scope.device.powerBtnData;
    }
    // mute
    else if (func == 'mute') {
      data = $scope.device.muteBtnData;
    }
    // other commands
    else {
      data = func;
    }

    if($scope.device.targetType === 1) {
      testData = { "systemId" : $scope.system.id, "type" : $scope.device.targetType,
        "addr" : $scope.device.testBstationMac, "port" : $scope.device.targetPort, "repeat" : $scope.device.info.attr.rpt_cnt,
        "ir_type": func.type || 0, "data" : data };
    }
    else {
      testData = { "systemId" : $scope.system.id, "type" : $scope.device.targetType,
        "addr" : $scope.device.targetAddr, "port" : $scope.device.targetPort, "repeat" : $scope.device.info.attr.rpt_cnt,
        "ramp_start" : $scope.device.info.attr.ramp_st, "ramp_speed" : $scope.device.info.attr.ramp_sp, "auto_cr" : $scope.device.info.attr.auto_cr,
        "data" : data };
    }

    var jsonTestData = JSON.stringify(testData);

    $http({
      method: 'POST',
      url: '/api/cloud/test',
      data: jsonTestData
    }).
      success(function(data) {
        if(data.result === true) {
          toastr.success('Test command sent');
        }
        else {
          toastr.error(data.error);
        }
      }).
      error(function() {
        toastr.error("Please try again");
      });
  };

  $scope.goSearchModel = function() {
    $state.go('menu.programming.add-device.device-model-search');
  };
});

/**
 * @ngdoc controller
 * @name DeviceModelSearchController
 * @description
 *  device model 검색
 */
app.controller('DeviceModelSearchController', function ($scope, $state, $modal, $http, toastr, Database) {

  $scope.device.model = null;
  $scope.device.info = null;
  $scope.query.value = '';


  $scope.doNext = function () {
    return Database.getDeviceInfo($scope.device.type.name, $scope.device.brand.name, $scope.device.model.id, $scope.device.targetType, $scope.device.model.type)
      .then(function(data) {
        var attrs = data.attr;
        console.log(attrs);
        if (attrs.codeset === 'ip') {
          $scope.device.targetPort = $scope.device.targetPort || parseInt(attrs.port, 10);
        } else {
          $scope.device.targetPort = 255;
          $scope.device.targetAddr = $scope.room.bstations[0].mac;
        }

        $scope.device.powerOff = false;
        if (data.meta.length) {
          _.each(data.meta, function(meta) {
            if (meta.strid === 'POWER_OFF' || meta.strid === 'POWER_TOGGLE') {
              $scope.device.powerOff = true;
            }
          });
        }

        $state.go('menu.programming.add-device.device-settings');
      })
      .catch(toastr.error);
  };

  // 테스트 팝업 화면 띄우기
  $scope.showTestModal = function() {

    // power on, mute, 나머지 commands 얻기 위해 getDeviceInfo
    Database.getDeviceInfo($scope.device.type.name, $scope.device.brand.name, $scope.device.model.id, $scope.device.targetType, $scope.device.model.type)
      .then(function(data) {
        $scope.device.info = data;
        $scope.device.powerBtn = false;
        $scope.device.powerBtnData = null;
        $scope.device.muteBtn = false;
        $scope.device.muteBtnData = null;

        _.each(data.btns, function(btn) {
          if (btn.def == 'POWER ON' || btn.def == 'POWER TOGGLE') {
            $scope.device.powerBtn = true;
            $scope.device.powerBtnData = btn.cmd;
          }
          if (btn.def == 'MUTE') {
            $scope.device.muteBtn = true;
            $scope.device.muteBtnData = btn.cmd;
          }
        });

        if (data.attr.codeset === 'ip') {
          $scope.device.targetPort = parseInt(data.attr.port, 10);
        } else {
          $scope.device.targetPort = -1;
        }

        var modal = $modal({
          scope: $scope,
          placement: 'top',
          template: 'views/modal-tpls/test-commands.html',
          container: 'body',
          show: false
        });
        modal.$promise.then(modal.show);
      })
      .catch(toastr.error);
  };

  $scope.device.testBstationMac = $scope.room.bstations[0].mac;

  // 테스트 실행
  $scope.btnTest = function(func) {
    var testData = {},
      data;

    if($scope.device.targetType === 2) {
      if (!$scope.device.targetAddr) {
        toastr.error('An IP address is required.');
        return;
      }
    }

    // power on
    if (func == 'power') {
      data = $scope.device.powerBtnData;
    }
    // mute
    else if (func == 'mute') {
      data = $scope.device.muteBtnData;
    }
    // other commands
    else {
      data = func;
    }

    if($scope.device.targetType === 1) {
      testData = { "systemId" : $scope.system.id, "type" : $scope.device.targetType,
        "addr" : $scope.device.testBstationMac, "port" : $scope.device.targetPort, "repeat" : $scope.device.info.attr.rpt_cnt,
        "ir_type": func.type || 0, "data" : data };
    }
    else {
      testData = { "systemId" : $scope.system.id, "type" : $scope.device.targetType,
        "addr" : $scope.device.targetAddr, "port" : $scope.device.targetPort, "repeat" : $scope.device.info.attr.rpt_cnt,
        "ramp_start" : $scope.device.info.attr.ramp_st, "ramp_speed" : $scope.device.info.attr.ramp_sp, "auto_cr" : $scope.device.info.attr.auto_cr,
        "data" : data };
    }

    var jsonTestData = JSON.stringify(testData);

    $http({
      method: 'POST',
      url: '/api/cloud/test',
      data: jsonTestData
    }).
      success(function(data) {
        if(data.result === true) {
          toastr.success('Test command sent');
        }
        else {
          toastr.error(data.error);
        }
      }).
      error(function() {
        toastr.error("Please try again");
      });
  };
});

/**
 * @ngdoc controller
 * @name DeviceSettingsController
 * @description
 *  device 정보 설정 후 생성
 */
app.controller('DeviceSettingsController', function ($scope, $state, toastr, Systems, Database, Devices) {

  $scope.isEntDevice = Database.checkIfEntertainment($scope.device.type.name);

  $scope.doNext = function () {

    if ($scope.isEntDevice) {   // entertainment device 인 경우

      $state.go('menu.programming.add-device.favchannels-option');

    } else {  // entertainment device 가 아닌 경우
      var d = angular.copy($scope.device);
      d.favEnable = 0;
      d.favDelay = 400;
      d.favEnter = 0;
      d.type = d.type.name;
      d.brand = d.brand.name;
      d.dbType = parseInt(d.model.type, 10);
      d.modelId = parseInt(d.model.id, 10);
      d.model = d.model.name;
      var jsonData = JSON.stringify(d);

      // device 생성
      return Devices.createOne($scope.room.id, jsonData)
        .then(function(data) {
          console.log(data);
          var id = Systems.getCurrentSystem().id;
          return Systems.updateSystem(id);  
        })
        .then(function (data) {
          $state.transitionTo('menu.programming.options', null, { reload: true, inherit: true, notify: true  });
          toastr.success('Successfully added ' + d.name + '.');
        })
        .catch(toastr.error);
    }
  };
});

/**
 * @ngdoc controller
 * @name FavChannelsOptionController
 * @description
 *  favorite channels 설정
 */
app.controller('FavChannelsOptionController', function ($scope, $state, $modal, toastr, Systems, Devices) {

  $scope.device.favEnable = $scope.device.favEnable || 1;
  $scope.device.favDelay = $scope.device.favDelay || 400;
  $scope.device.favEnter = $scope.device.favEnter || 1;

  $scope.finish = function () {

    var d = angular.copy($scope.device);
    d.type = d.type.name;
    d.brand = d.brand.name;
    d.dbType = parseInt(d.model.type, 10);
    d.modelId = parseInt(d.model.id, 10);
    d.model = d.model.name;

    var jsonData = JSON.stringify(d);
    console.log(jsonData);

    // device 생성
    return Devices.createOne($scope.room.id, jsonData)
      .then(function(data) {
        console.log(data);
        var id = Systems.getCurrentSystem().id;
        return Systems.updateSystem(id);  
      })
      .then(function (data) {
        $state.transitionTo('menu.programming.options', null, { reload: true, inherit: true, notify: true  });
        toastr.success('Successfully added ' + d.name + '.');
      })
      .catch(toastr.error);
  };
});

'use strict';


app.controller('AddMacroRoomController', 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.add-macros.macro-type');
    })
    .catch(toastr.error);
  };
});

app.controller('MacroTypeController', function ($scope, $state, toastr, Systems) {
  var steps = $scope.addMacro.steps;
  while(steps.length > 0) {
    steps.pop();
  }
  $scope.addMacro.currentDevice = {};
  $scope.addMacro.button = {};
  $scope.addMacro.doneScreen = {'index': 0,'device': {}, 'devices': []};
  $scope.addMacro.disablePopup = false;

  $scope.navigateTo = function(state) {

    var base = 'menu.advanced.add-macros';
    switch (state) {
      case 'Turn Off All':
        $scope.macroType.id = 0;
        Systems.updateCurrentMacroForPower($scope.addMacro.room.id).then( function(data) {
          console.log(data);
          $state.go(base + '.finish');
        }).catch(toastr.error);

        break;
      case 'Device Activity':
        $scope.macroType.id =  1;
        $state.go(base + '.choose-device');
        break;
      case 'Custom Button':
        $scope.macroType.id = 2;
        $state.go(base + '.button-name');
        break;
      default:
        //do nothing
    }
  };

});

app.controller('ButtonNameController', function ($scope, $state) {
  $scope.doNext = function() {
    $state.go('menu.advanced.add-macros.finish');
  };
});


app.controller('ChooseMacroDeviceController', function ($scope, $state) {
  $scope.doNext = function() {
    $state.go('menu.advanced.add-macros.finish');
  };
});


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

  $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() {
    if ($scope.macroType.id === 1) {
      $state.go('menu.advanced.add-macros.choose-device');
    } else if ($scope.macroType.id === 2) {
      $state.go('menu.advanced.add-macros.button-name');
    } else {
      $state.go('menu.advanced.add-macros.macro-type');
    }
  };

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

});

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

  $scope.goBack = function() {
    $state.go('menu.advanced.add-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.add-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.currentDevice.id, jsonData).then(handleSuccess, handleError);
      } else {
        jsonData = { "text": $scope.addMacro.button.name, "auto_wait": 1 , "edit_type": 1, "popup": 0, "activity": [], "macro": steps } ;
        Systems.createCustomButtonMacro($scope.addMacro.room.id, $scope.addMacro.room.main_device_id, jsonData).then(handleSuccess, handleError);
      }
    } else {
      $state.go('menu.advanced.add-macros.macro-commands');
    }
  };

});


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

  $scope.goBack = function() {
    if ($scope.addMacro.doneScreen.index === 0) {
      $state.go('menu.advanced.add-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 } );
      console.log(jsonData);

      var handleSuccess = function(response) {
        if(response.data.result === true) {
          $state.go('menu.advanced.add-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.currentDevice.id, jsonData).then(handleSuccess, handleError);
      } else {
        jsonData = JSON.stringify( { text: $scope.addMacro.button.name, auto_wait: 1 , edit_type: 1, popup: 1, activity: activityData, macro: steps } );
        Systems.createCustomButtonMacro($scope.addMacro.room.id, $scope.addMacro.room.main_device_id, jsonData).then(handleSuccess, handleError);
      }
    } else {
      $scope.addMacro.doneScreen.index++;
    }

  };
});


'use strict';


app.controller('SelectRemoteController', function ($scope, $filter, $state, availableModels, toastr, Systems, Rooms) {
  $scope.remote = {
    name: '',
    modelType: availableModels[0]
  };

  $scope.availableModels = availableModels;

  $scope.goBack = function () {
    $state.go('menu.programming.options');
  };

  $scope.finish = function () {

    var currentSystem = Systems.getCurrentSystem(),
        jsonData = JSON.stringify({ name: $scope.remote.modelType , type: $scope.remote.modelType });

    var setRemote = function(roomId, json) {
      return Rooms.setRemote(roomId, json).then(function(data) { 
        toastr.success('Successfully added the remote');
        return currentSystem.id;
      });
    };

    var updateSystem = function(id) {
      return Systems.updateSystem(id).then(function (data) {
        console.log(data);
        return $state.transitionTo('menu.programming.options', {}, { reload: true, inherit: true, notify: true  });
      });
    };

    setRemote($scope.room.id, jsonData)
      .then(updateSystem)
      .catch(function(error) {
        toastr.error(error, 'Error');
      });
  };

});

'use strict';


app.controller('SelectRoomController', function ($scope, $state, toastr, availableModels, Systems, Rooms ) {
  $scope.modelType = availableModels[0];
  $scope.availableModels = availableModels;

  $scope.finish = function() {
    var currentSystem = Systems.getCurrentSystem();
    var jsonData = JSON.stringify({ name: $scope.roomName,
                                    bstationName: $scope.modelType,
                                    type: $scope.modelType });
    
    var createRoom = function(json) {
      return Rooms.create(json).then(function(data) { 
        toastr.success('Successfully added ' + $scope.roomName);
        return currentSystem.id;
      });
    };

    var updateSystem = function(id) {
      return Systems.updateSystem(id).then(function (data) {
        console.log(data);
        //return $state.transitionTo('menu.advanced.add-room.link-remote', {}, { reload: true, inherit: true, notify: true  });
        $state.go('menu.advanced.options');
      });
    };

    createRoom(jsonData)
      .then(updateSystem)
      .catch(toastr.error);

  };
});

'use strict';

app.controller('DeviceSelectionController', function ($scope, $state, toastr, Devices) {
  $scope.doNext = function() {
    Devices.getOne($scope.deviceMenu.roomId, $scope.deviceMenu.deviceId).then(function (data) {

      Devices.setCurrentData(data);
      $state.go('menu.advanced.device.edit-layout');

    }).catch(toastr.error);
  };

});



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

  $scope.finish = function() {

    var pages = [],
        hardPages = angular.copy($scope.deviceMenu.hard.pages),
        hardBtns = _.flatten(hardPages, 'btns'),
        menuPages = angular.copy($scope.deviceMenu.menu.pages),
        pageId = 0,
        buttonId = 8192;

    function rewriteMacro(btn) {
      var newMacro = btn.macro ? JSON.parse(btn.macro)[0] : {};

      if (_.isEmpty(newMacro)) {
        newMacro.type = 1;
        newMacro.device_id = parseInt($scope.deviceMenu.deviceData.id, 10);
      }

      newMacro.func = btn.func.id;

      if (btn.repeatSetting === 'custom') {
        newMacro.repeat_min = btn.repeat_min;
        newMacro.repeat_macro = btn.repeat_macro;
      } else {
        delete newMacro.repeat_min;
        delete newMacro.repeat_macro;
      }

      if (!btn.press_hold) {
        newMacro.press_hold = 0;
      }


      console.log(newMacro);
      return JSON.stringify([newMacro]);
    }

    _.remove(hardBtns, function(button) {
      return !button.display_text;
    });

    _.forEach(hardBtns, function(hardBtn) {
      hardBtn.macro = rewriteMacro(hardBtn);
      hardBtn.page_btn_idx = -1;
      delete hardBtn.func;
      delete hardBtn.repeatSetting;
      delete hardBtn.repeat_min;
      delete hardBtn.repeat_macro;
      delete hardBtn.press_hold;
      delete hardBtn.name;
    });


    pages.push({ id: -1, btns: hardBtns });

    _.forEach(menuPages, function(page) {
      if (_.filter(page.btns, 'display_text').length) {
        page.id = pageId;
        pageId++;

        _.remove(page.btns, function(button) {
          return !button.display_text;
        });

        _.forEach(page.btns, function(btn) {

          if (btn.display_text) {

            btn.id = buttonId;
            buttonId++;


            btn.macro = rewriteMacro(btn);

            delete btn.func;
            delete btn.repeatSetting;
            delete btn.repeat_min;
            delete btn.repeat_macro;
            delete btn.press_hold;
          }

        });

        pages.push(page);
      }
    });

    console.log(pages);

   
    var returnDevice = angular.copy($scope.deviceMenu.deviceData); 
    _.assign(returnDevice, {pages: pages});

    //if these properties are seleceted as `None` on the client their properties will be null
    //in that case, they to be changed to -1 
    
    returnDevice.meta_pwr_on =  returnDevice.meta_pwr_on || -1;
    returnDevice.meta_pwr_off = returnDevice.meta_pwr_off || -1;
    returnDevice.meta_pwr_toggle = returnDevice.meta_pwr_toggle || -1;
    returnDevice.meta_in_toggle = returnDevice.meta_in_toggle || -1;
    

    var jsonData = JSON.stringify({ data: returnDevice });

    Devices.storeOne($scope.deviceMenu.roomId, $scope.deviceMenu.deviceId, jsonData).then(function(data) {
      $state.go('menu.advanced.options');
    }, function (error) {
      toastr.error(error, 'Error');
    });   

  };

});

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

  };
});

'use strict';
/**
 * @ngdoc controller
 * @name LoginController
 * @description
 *  로그인, 비밀번호 리셋 관련
 */
app.controller('LoginController', function ($rootScope, $scope, $state, $stateParams, toastr, Systems, Auth, User) {
  // 로그인이 필요한 url 에 로그인 없이 접근하면 e=401 파리미터를 가지고 /login 으로 오는데 그때에 대한 처리
  if (!_.isEmpty($stateParams)) {
    if ($stateParams.e === '401') {
      $scope.error = '<div class="alert alert-warning"><i class="fa fa-lg fa-warning"></i>&nbsp;&nbsp;You must log in to access this page.</div>';
    }
  }

  // 이미 로그인한 사용자면 system-overview 메뉴로 이동시킴
  Auth.currentUser().then(function(user) {
    if(user) {
      $state.go('home');
    }
  });

  // 로그인 화면에서 아이디/패스워드 입력 후 Sign in 버튼 클릭하면 실행되는 함수
	$scope.login = function() {
		var jsonData = JSON.stringify( $scope.credentials );  // 아이디/패스워드
		console.log(jsonData);

    // 로그인
		User.login(jsonData)
      .then( function(data) {
        if(data.result) {
          $state.go('home');
				} else {
          toastr.error(data.error);
          $scope.credentials.password = '';
          $scope.loginForm.$setPristine();
				}
			})
      .catch(toastr.error);
	};

});

'use strict';

app.controller('MainMenuLayoutController', function ($scope, $state, $filter, $timeout, Systems, Devices) {

  $scope.mainMenu.changingIcon = false;
  $scope.mainMenu.mainDevice.btns = [];
  $scope.mainMenu.mainDevice.id = Systems.getMainDevice().id;

  Devices.getInfoJson().success(function (data) {
    Devices.setIcons(data);
    $scope.mainMenu.deviceIcons = Devices.getIcons();

    console.log($scope.mainMenu.deviceIcons);
  }).error(function () {

  });

  var btnIndexOffset = 0;

  _.forEach(Systems.getMainDevice().pages, function(page) {
     _.forEach(page.btns, function(btn) {
      console.log(btn);
      btn.hidden_option = btn.hidden_option ? true:false;
      btn.page_btn_idx += btnIndexOffset;
      $scope.mainMenu.mainDevice.btns.push(btn);
     });
     btnIndexOffset += 6;
  });

  $scope.mainMenu.mainDevice.btns = _($scope.mainMenu.mainDevice.btns).sortBy('page_btn_idx').value();
  console.log($scope.mainMenu.mainDevice.btns);

  $scope.deleteDevice = function (btn) {
    _.remove($scope.mainMenu.mainDevice.btns, { id: btn.id });
  };

  $scope.makeCopy = function(obj) {
    return angular.copy(obj);
  };

  $scope.isEmpty = function(obj) {
    return _.isEmpty(obj);
  };


  $scope.switchToImageView = function() {
    $scope.mainMenu.selectedImgName = angular.copy($scope.mainMenu.selectedBtn.image_name);
    $scope.mainMenu.changingIcon = true;
  };
  
  $scope.saveImage = function() {
    $scope.mainMenu.selectedBtn.image_name = angular.copy($scope.mainMenu.selectedImgName);
    $scope.mainMenu.changingIcon = false;
  };

  $scope.replaceButton = function (btnId) {
    var idx = _.findIndex($scope.mainMenu.mainDevice.btns, {'id': btnId});
    $scope.mainMenu.mainDevice.btns[idx] = $scope.mainMenu.selectedBtn;
  };

  $scope.clearSelectedBtn = function() {
    $timeout(function() {
        $scope.mainMenu.selectedBtn = {};
    }, 200);
  };

  $scope.finish = function() {
    var numPages = Math.ceil($scope.mainMenu.mainDevice.btns.length / 6);
    var pages = [];

    for (var pageId = 0; pageId < numPages; pageId++ ) {
      var page = {id: pageId};
      var start = pageId * 6;

      page.btns = $scope.mainMenu.mainDevice.btns.slice(start, start+6);
      for (var index = 0; index < page.btns.length; index++) {
        page.btns[index].page_btn_idx = index;
      }
      pages.push(page);
    }
    console.log(pages);

    Systems.setMainDevice({id: $scope.mainMenu.mainDevice.id, pages: pages});
    Systems.storeMainDevice($scope.mainMenu.room.id).then(function(data) { 

      Systems.updateSystem(Systems.getCurrentSystem().id).then(
        function (data) {
          console.log(data);
          $state.transitionTo($state.current, null, { reload: true, inherit: true, notify: true  });
        },
        function (error) {
          alert(error);
        }
      );

    }, function(error) {
      alert(error);
    });

  };
});

'use strict';

app.controller('PowerOffController',  function ($scope, Devices) {
  Devices.initFunctions();
  $scope.powerOff = { 'devices': [], 'device': {} };
  $scope.powerOff.index = 0;
});


app.controller('PowerOffDevicesController', function ($scope, $state, $http, Systems, Devices, currentMacro) {

  var currentSystem = Systems.getCurrentSystem(),
       dataActivity = currentMacro;
  console.log(dataActivity);

  if(dataActivity && dataActivity.edit_type === 0 && dataActivity.activity.length ) {
    _.forEach(dataActivity.activity, function(data) {
      var device = Systems.getDevice($scope.room.id, data.device_id);

      if (device) {
        $scope.powerOff.devices.push({
          'device_id': data.device_id,
          'name': device.name,
          'type': data.type,
          'func': data.func,
          'repeat_min': device.repeat_min,
          'repeat_macro': device.repeat_macro,
          'target_type': device.target_type,
          'target_addr': device.target_addr,
          'target_port': device.target_port
        });
      }
    });
  }
  // else {
  //   _.forEach($scope.room.devices, function(device) {
  //     if ( _.isEmpty($scope.powerOff.devices)) {
  //       $scope.powerOff.devices.push({
  //         'device_id': device.id,
  //         'name': device.name,
  //         'type': 0,
  //         'func': null,
  //         'repeat_min': device.repeat_min,
  //         'repeat_macro': device.repeat_macro,
  //         'target_type': device.target_type,
  //         'target_addr': device.target_addr,
  //         'target_port': device.target_port,
  //       });
  //     }
  //   });
  // }

  $scope.doNext = function() {

    $state.go('menu.programming.power-off.commands');
  };

});

app.controller('PowerOffDeviceCommandsController', function ($scope, $state, Systems, Devices) {

  $scope.goBack = function() {
    if ($scope.powerOff.index === 0) {
      $scope.powerOff.devices = [];
      Devices.initFunctions();
      $state.go('menu.programming.power-off.devices-to-use' );
    } else {
      $scope.powerOff.index--;
    }
  };


  $scope.incrIdx = function() { $scope.powerOff.index++; };

  $scope.finish = function() {
    //Save to server

    var sendData = angular.copy($scope.powerOff.devices);

    for (var i=0,  tot=sendData.length; i < tot; i++) {
      sendData[i].func = sendData[i].func.id;
      delete sendData[i].name;
      delete sendData[i].repeat_min;
      delete sendData[i].repeat_macro;
      delete sendData[i].target_type;
      delete sendData[i].target_addr;
      delete sendData[i].target_port;
      delete sendData[i].funcs;
    }

    var jsonData = JSON.stringify( { auto_wait : 1, edit_type : 0, popup : 1, activity : sendData, macro : [] } );
    console.log(jsonData);

    Systems.storePowerMacro($scope.room.id, jsonData).then(function(response) {
      if(response.data.result === true) {
        $state.go('menu.programming.options');
      }
      else {
        alert('Your edit/create action failed.  Please try again.');
      }
    }, function(error){
      alert("Please try again");
    });
  };

});

'use strict';


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

  	$scope.systems = resolvedSystems;

    $scope.doNext = function(){
      Systems.setCurrentRoom(null);
      return Systems.updateSystem($scope.choice).then(
        function (data) {
          var masterBstation;
          _.each(data.rooms, function(room) {
            if (!masterBstation) {
              masterBstation = _.where(room.bstations, {
                master: 1
              })[0];
            }
          });
          if (!masterBstation) {
            $state.go('recovery-bstation.select', {rooms: angular.toJson(data.rooms)});
            return;
          }
        
          $state.go('menu.job-overview');
        },
        function (error) {
          toastr.error(error);
        }
      );
    };

});


app.controller('SystemDeleteController', function ($scope, $state, toastr, resolvedSystems, Systems, User) {

    $scope.systems = resolvedSystems;
    $scope.sysToDel = {};

    $scope.deleteSystem = function(){

      Systems.deleteSystem($scope.sysToDel.id).then(function (data) {

          if (Systems.getAll().length === 0) {
            User.logout().then(function() {
              $state.transitionTo('register', null, { reload: true, inherit: true, notify: true  });
            }); 
          } else if (Systems.getCurrentSystem().id === $scope.sysToDel.id) {
            $state.go('system-select');
          } else {
            $state.go('menu.job-overview');
          }     
        },
        function (error) {
          toastr.error(error);
        }
      );
    };

});

app.controller('SystemSettingsController', function ($scope, $modal, timeZones, currentSystem) { 
  
  $scope.system = currentSystem;
  $scope.timeZones = timeZones;

});

app.controller('JobOverviewController', function ($scope, $http, $modal, $popover, $state, toastr, Systems, Rooms, Database, Devices) {
  $scope.system = Systems.getCurrentSystem();
  $scope.selections = { 'selectedRoom': {}, 'selectedBstation': {}, 'selectedRemote': {}, 'selectedDevice': {}};
  $scope.jobId = Systems.getCurrentJobId();

  var favoriteOptionModal = $modal({
    scope: $scope,
    title: 'Add Favorite Channels to this device',
    placement: 'top',
    template: 'views/assistant/modal-tpls/job-overview/fav-option.html',
    container: '#job-overview',
    show: false
  });

  $scope.popover = { 'device': ''};

  $scope.findPunchDevice = function(room) {
    $scope.popover.punchName = _.find(room.devices, { 'id': $scope.popover.device.punch_vol }).name;
  };

  $scope.containsMaster = function(room) {
    return _.contains(_.pluck(room.bstations, 'master'), 1);
  };

  $scope.changeValue = function(value) {
    return value/1000;
  };

  $scope.isEntDevice = Database.checkIfEntertainment;

  $scope.showFavModal = function (room, device) {
    angular.copy(room, $scope.selections.selectedRoom);
    angular.copy(device, $scope.selections.selectedDevice);

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


  $scope.toggleFavorite = 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];

    if (!_.isEqual(currentDevice, device)) {
      var jsonData =  { "favOption": device.fav_option, "favDelay": device.fav_delay, "favEnter": device.fav_enter  };
      console.log(jsonData);
      $http({
        method: 'POST',
        url: '/urcassistant/api/device/favorite/' + room.id + '/' + device.id,
        data : jsonData
      }).
      success(function(data) {
        if(data.result) {
          currentDevice.fav_option = device.fav_option;
          currentDevice.fav_delay = device.fav_delay;
          currentDevice.fav_enter = device.fav_enter;
          Systems.loadSystem(currentSystem);
          $state.transitionTo($state.current, null, { reload: true, inherit: true, notify: true  });
        }
        else {
          toastr.error(data.error);
        }
      })
      .error(function(error) {
        toastr.error('Please try again');
      });
    }

  };
  
});

/**
 * @ngdoc controller
 * @name JobListController
 * @description
 *  Job List 화면
 */
app.controller('JobListController', function($scope, $location, $timeout, $modal, $state, availableModels, toastr, ngTableParams, Systems) {
  $scope.requests = {};
  $scope.selectedJobId = '';
  $scope.selectedCompanyName = '';
  $scope.jobOptionAction = 'start-job';
  $scope.availableModels = availableModels;

  $scope.empty = {
    type: 'HCM-C1',
    roomName: ''
  };

  $scope.searchOptions = [
    {
      name: 'Company Name',
      value: 'company_name'
    },
    {
      name: 'Job ID',
      value: 'job_id'
    },
    {
      name: 'Client ID',
      value: 'username'
    }
  ];
  $scope.filterType = 'company_name';

  $scope.search = function() {
    $scope.tableParams.filter({
      name: $scope.filterType,
      min: $scope.filterValue
    });
  };

  function parseSelection(str) {
    //str will be, for example, +status or -status
    return {
      name: str.substr(1),
      reverse: str.charAt(0) === '-' ? true:false
    };
  }

  // 목록 테이블 생성
  //ngTableParams: parameters, settings
  $scope.tableParams = new ngTableParams(
    {
      page: 1,            // show first page
      count: 10          // count per page
    },
    {
      total: 0,           // length of data
      getData: function($defer, params) {
        console.log(params.filter());
        var page = params.page();
        var total = params.total();
        var previousData = params.data;

        var options = { count: params.count() };
        var orderBy = params.orderBy();
        var sortingColumn = !_.isEmpty(orderBy) && parseSelection(orderBy[0]);
        var filter = params.filter();

        if (sortingColumn) {
          angular.extend(options, { orderBy: sortingColumn });
        }
        if (!_.isEmpty(filter)) {
          angular.extend(options, { filter: {
            name: filter.name,
            min: filter.min
          } });
        }
        if (page > 1  ) {
          angular.extend(options, {from: (page-1) * params.count()});
        }

        Systems.jobList(options)
          .then(function(data) {
            //If previous total does not equal

            params.total(data.length);
            $timeout(function() {
              console.log(params.total());

              //if (params.total() !== count) params.page(1);

              //$defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
              $defer.resolve(data);
            }, 500);
          })
          .catch(function(error) {
            toastr.error(error);
            $defer.resolve(previousData);
          });
      }
    });

  // 목록에서 waiting 클릭해서 팝업 띄우기 / 팝업에서 GO 클릭
  $scope.jobOption = function(jobId, action, companyName) {
    var modal = $modal({
        scope: $scope,
        title: 'Job Option',
        template: 'views/assistant/modal-tpls/job-option.html',
        container: '.container',
        show: false
      }),
      jsonData;

    $scope.selectedJobId = jobId;
    $scope.selectedCompanyName = companyName;

    // 목록에서 waiting 클릭
    if (!action) {
      modal.$promise.then(modal.show);
    }
    // 팝업에서 GO 클릭
    else {
      // jobId 로 부터 job 생성
      if (action == 'start-job') {
        jsonData = JSON.stringify({jobId: jobId, startWithEmpty: 0});

        Systems.import(jsonData)
          .then(function(data) {
            console.log('start job success', data);

            $scope.goOverview(jobId);
          })
          .catch(toastr.error);
      }
      // system 생성
      else if (action == 'start-job-empty') {
        $scope.empty.roomName = '';

        var modal2 = $modal({
            scope: $scope,
            title: 'Start empty options',
            template: 'views/assistant/modal-tpls/start-job-empty.html',
            container: '.container',
            show: false
          });

        modal2.$promise.then(modal2.show);
      }
      // view job request
      else if (action == 'view-job-request') {
        Systems.setCurrentJobId($scope.selectedJobId);
        $scope.viewJobData();
      }
    }
  }

  // start job empty 선택후 열린 팝업에서 OK 클릭
  $scope.jobEmptyImport = function() {
    var jobId = $scope.selectedJobId,
      params = {
        jobId: jobId,
        startWithEmpty: 1,
        roomName: $scope.empty.roomName,
        modelType: $scope.empty.type,
        bstationName: $scope.empty.type
      },
      jsonData = JSON.stringify(params);

    Systems.import(jsonData)
      .then(function(data) {
        console.log('start job empty success', data);

        $scope.goOverview(jobId);
      })
      .catch(toastr.error);
  };

  // 목록에서 opened 클릭
  $scope.goOverview = function(jobId) {
    Systems.setCurrentJobId(jobId);

    var jsonData = JSON.stringify({jobId: jobId});

    Systems.getSystems(jsonData)
      .then(function(data) {console.log('get systems', data);
        // systems 배열에 있는 첫 번째 system 의 id 를 구함
        var systemId = data.systems[0].id;

        // 현재 system 으로 update
        Systems.setCurrentRoom(null);
        return Systems.updateSystem(systemId, jsonData).then(
          function (data) {
            $state.go('menu.job-overview');
          },
          function (error) {
            toastr.error(error);
          }
        );
      })
      .catch(toastr.error);
  };

  // 목록에서 ready 클릭해서 팝업 띄우기 / 팝업에서 버튼 클릭
  $scope.jobReady = function(jobId, action) {
    var modal = $modal({
      scope: $scope,
      title: 'Job Option',
      template: 'views/assistant/modal-tpls/job-ready.html',
      container: '.container',
      show: false
    });

    $scope.selectedJobId = jobId;

    // 목록에서 ready 클릭
    if (!action) {
      modal.$promise.then(modal.show);
    }
    // 팝업에서 버튼 클릭
    else {
      // view job request data
      if (action == 'view') {
        $scope.viewJobData(jobId);
      }
      // reopen
      else if (action == 'reopen') {
        var jsonData = JSON.stringify({jobId: jobId, status: 1});

        Systems.setStatus(jsonData)
          .then(function(data) {
            $scope.goOverview(jobId);
          })
          .catch(toastr.error);
      }
    }
  }

  // 검색, 정렬 초기화
  $scope.clearSorting = function() {
    $scope.filterType = 'title';
    $scope.filterValue = '';
    $scope.searchForm.$setPristine();

    $scope.tableParams.filter({});
    $scope.tableParams.sorting({});
  };
});

/**
 * @ngdoc controller
 * @name CompanyListController
 * @description
 *  Company List 화면
 */
app.controller('CompanyListController', function($scope, $location, $timeout, $modal, $state, availableModels, toastr, ngTableParams, User, Systems) {
  $scope.requests = {};
  $scope.availableModels = availableModels;

  $scope.empty = {
    companyId: null,
    userId: null,
    systemName: null,
    timezone_id: -1,
    timezone_dst: 1,
    time_type: 0,
    roomName: null,
    modelType: 'HCM-C1',
    bstationName: null
  };
  $scope.empty.bstationName = $scope.empty.modelType;

  $scope.searchOptions = [
    {
      name: 'Company Name',
      value: 'company_name'
    },
    {
      name: 'Client ID',
      value: 'username'
    }
  ];
  $scope.filterType = 'company_name';

  $scope.search = function() {
    $scope.tableParams.filter({
      name: $scope.filterType,
      min: $scope.filterValue
    });
  };

  function parseSelection(str) {
    //str will be, for example, +status or -status
    return {
      name: str.substr(1),
      reverse: str.charAt(0) === '-' ? true:false
    };
  }

  // 목록 테이블 생성
  //ngTableParams: parameters, settings
  $scope.tableParams = new ngTableParams(
    {
      page: 1,            // show first page
      count: 10          // count per page
    },
    {
      total: 0,           // length of data
      getData: function($defer, params) {
        console.log(params.filter());
        var page = params.page();
        var total = params.total();
        var previousData = params.data;

        var options = { count: params.count() };
        var orderBy = params.orderBy();
        var sortingColumn = !_.isEmpty(orderBy) && parseSelection(orderBy[0]);
        var filter = params.filter();

        if (sortingColumn) {
          angular.extend(options, { orderBy: sortingColumn });
        }
        if (!_.isEmpty(filter)) {
          angular.extend(options, { filter: {
            name: filter.name,
            min: filter.min
          } });
        }
        if (page > 1  ) {
          angular.extend(options, {from: (page-1) * params.count()});
        }

        User.companyList(options)
          .then(function(data) {
            //If previous total does not equal

            params.total(data.length);
            $timeout(function() {
              console.log(params.total());

              //if (params.total() !== count) params.page(1);

              //$defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
              $defer.resolve(data);
            }, 500);
          })
          .catch(function(error) {
            toastr.error(error);
            $defer.resolve(previousData);
          });
      }
    });

  // 목록 클릭
  $scope.startOptionsModal = function(companyId, id) {
    $scope.empty.companyId = companyId;
    $scope.empty.userId = id;

    var modal = $modal({
        scope: $scope,
        title: 'Start options',
        template: 'views/assistant/modal-tpls/start-options.html',
        container: '.editor-container',
        show: false
      });

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

  // system 생성
  $scope.create = function() {
    var jsonData = JSON.stringify($scope.empty);

    Systems.createOne(jsonData)
      .then(function(data) {
        var jobId = data;

        $scope.goOverview(jobId);
      })
      .catch(toastr.error);
  };

  // Job Overview 화면으로 이동
  $scope.goOverview = function(jobId) {
    Systems.setCurrentJobId(jobId);

    var jsonData = JSON.stringify({jobId: jobId});

    Systems.getSystems(jsonData)
      .then(function(data) {console.log('get systems', data);
        // systems 배열에 있는 첫 번째 system 의 id 를 구함
        var systemId = data.systems[0].id;

        // 현재 system 으로 update
        Systems.setCurrentRoom(null);
        return Systems.updateSystem(systemId, jsonData).then(
          function (data) {
            $state.go('menu.job-overview');
          },
          function (error) {
            toastr.error(error);
          }
        );
      })
      .catch(toastr.error);
  };
});
'use strict';

app.controller('PunchToDeviceController', function ($scope, $state, deviceId) {
  $scope.doNext = function() {
    $state.go('menu.programming.volume-control.punch-from-device');
  };
});



app.controller('PunchFromDeviceController', function ($scope, $state, $http, Systems) {
  

  var punchVolId = $scope.volumeControl.punchTo.punch_vol;

  if (!_.isEmpty($scope.volumeControl.punchTo) && punchVolId !== -1 ) {
    //check to see if it's not empty to avoid error on state reload
    var punchFromDevice = _.find($scope.volumeControl.devices.source, { 'id': $scope.volumeControl.punchTo.punch_vol });
    console.log(punchFromDevice);
    $scope.volumeControl.punchFrom = punchFromDevice ;
  }


  $scope.finish = function() {
    var punchTo = $scope.volumeControl.punchTo;
    var punchFrom = $scope.volumeControl.punchFrom;

    if (punchTo.punch_vol === punchFrom.id ) {
      //if data is same, skip send to server 
      console.log('skipping send to server');
      $state.go('menu.programming.options');

    } else {
      //else send to server and update client
      var jsonData = JSON.stringify( { punchFrom : punchFrom.id });
    
      $http({
        method: 'POST',
        url: '/urcassistant/api/device/punch/' + $scope.room.id + '/' + punchTo.id,
        data : jsonData
      }).
      success(function(data) {
        if(data.result) {

          if (punchTo.id) { 
            //if the punchTo device is not the Main device, update the client
            var currentSystem = Systems.getCurrentSystem();        
            var roomIndex = _.findIndex(currentSystem.rooms, { 'id': $scope.room.id });      
            var deviceIndex = _.findIndex(currentSystem.rooms[roomIndex].devices, { 'id': punchTo.id });
            var currentDevice = currentSystem.rooms[roomIndex].devices[deviceIndex];        
            currentDevice.punch_vol =  punchTo.id !== punchFrom.id ? punchFrom.id : -1;

            Systems.loadSystem(currentSystem);
          }

          
          $state.transitionTo('menu.programming.options', null, { reload: true, inherit: true, notify: true  });

        }
        else {
          alert(data.error);
        }
      }).
      error(function() {
        alert("Please try again");
      });
    } 
  };
  
});