'use strict';
/**
 * @ngdoc controller
 * @name PunchToDeviceController
 * @description
 *  punch to device 선택 화면
 */
app.controller('PunchToDeviceController', function ($scope, $state, deviceId) {
  $scope.checkPunchTo = function(id) {
    var index = $scope.volumeControl.punchTo.indexOf(id);

    if (index < 0) {
      $scope.volumeControl.punchTo.push(id);
    } else {
      $scope.volumeControl.punchTo.splice(index, 1);
    }

    $scope.volumeControl.punchTo.sort(function(a, b) {
      return a - b;
    });
  };

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

/**
 * @ngdoc controller
 * @name PunchFromDeviceController
 * @description
 *  punch from device 선택 화면
 */
app.controller('PunchFromDeviceController', function ($rootScope, $scope, $state, $http, Systems) {
  $scope.volumeControl.punchToNames = [];

  _.each($scope.volumeControl.punchTo, function(id) {
    var name = _.findWhere($scope.volumeControl.devices.destination, {
      id: id
    })['name'];

    $scope.volumeControl.punchToNames.push(name);
  });


  
  // punch to 에서 선택되었는지 검사
  function currentlySelected(punchFromId) {
    var selected = false;

    if ($scope.volumeControl.punchTo.indexOf(punchFromId) > -1) {
      selected = true;
    }

    return selected;
  }

  _.each($scope.volumeControl.devices.source, function(device) {
    if (device.id != -1) {
      device.currentlySelected = currentlySelected(device.id);
    }
  });


  $scope.setExtraInfo = function(device, punchFrom) {
    var extraInfo = device.extra_info,
      jsonData;

    if (extraInfo) {
      //extraInfo = JSON.parse(extraInfo);

      _.each(extraInfo.punch, function(room) {
        if (room.roomId == $scope.room.id) {
          room.from = punchFrom;
        }
      });
    } else {
      extraInfo = {
        punch: []
      };

      _.each($scope.system.rooms, function(room) {
        extraInfo.punch.push({
          roomId: room.id,
          from: (room.id == $scope.room.id) ? punchFrom : ''
        });
      });
    }

    jsonData = JSON.stringify(extraInfo);

    // set_extra_info API 호출
    $http({
      method: 'POST',
      url: '/api/twoway_device/set_extra_info/' + device.room_id + '/' + device.id,
      data : {
        data: jsonData
      }
    }).
    success(function(data) {

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

  $scope.finish = function() {
    var punchFrom = $scope.volumeControl.punchFrom,
      punchToData,
      jsonData;

    $scope.volumeControl.punchToTrfzw = [];
    $scope.volumeControl.punchToTwowayDevices = [];
    $scope.volumeControl.punchToNormaDevices = [];

    _.each($scope.volumeControl.punchTo, function(id) {
      var device = _.findWhere($scope.volumeControl.devices.destination, {
        id: id
      });

      if (device.model === 'TRF-ZW1') {
        $scope.volumeControl.punchToTrfzw.push(id);
      }

      if (device.twoway_device && !device.other_room) {
        $scope.volumeControl.punchToTwowayDevices.push(id);
      } else {
        $scope.volumeControl.punchToNormaDevices.push(id);
      }
    });

    // punch 세팅 API 호출
    function punch(url, jsonData, transition) {
      $http({
        method: 'POST',
        url: url,
        data : jsonData
      }).
      success(function(data) {
        if(data.result) {

          if (transition) {
            var currentSystem = Systems.getCurrentSystem();
            Systems.updateSystem(currentSystem.id).then(function (data) {
              $state.transitionTo('menu.programming.options', null, { reload: true, inherit: true, notify: true  });
            });
          }

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

    // step1: TRF-ZW
    //          => $scope.setExtraInfo 호출
    // step2: twoway device
    //          => 다른 room 에 있는 TRF-ZW1 일 경우 '/api/twoway_device/punch/' 는 호출하지 않음
    //          => 나머지 device 는 '/api/twoway_device/punch_multi/' 를 호출
    // step3: normal device

    // step1
    _.each($scope.volumeControl.punchToTrfzw, function(id) {
      var device = _.findWhere($scope.volumeControl.devices.destination, {
        id: id
      });

      // TRF-ZW1 인 경우 set_extra_info 를 수행함
      $scope.setExtraInfo(device, punchFrom.id);
    });

    // step1 이 끝나고 step2, step3 가 없으면 programming options 화면으로 이동
    if (!$scope.volumeControl.punchToTwowayDevices.length && !$scope.volumeControl.punchToNormaDevices.length) {
      var currentSystem = Systems.getCurrentSystem();
      Systems.updateSystem(currentSystem.id).then(function (data) {
        $state.transitionTo('menu.programming.options', null, { reload: true, inherit: true, notify: true  });
      });
    }
    // step2 또는 step3 가 있는 경우
    else {
      // step2 가 있는 경우
      if ($scope.volumeControl.punchToTwowayDevices.length) {
        punchToData = $scope.volumeControl.punchToTwowayDevices;
        jsonData = JSON.stringify( { punchFrom : punchFrom.id, punchTo : punchToData });

        // punch 세팅 API 호출
        $http({
          method: 'POST',
          url: '/api/twoway_device/punch_multi/' + $scope.room.id,
          data : jsonData
        }).
        success(function(data) {
          if(data.result) {

            // step2 가 끝나고 step3 가 없으면 programming options 화면으로 이동
            if (!$scope.volumeControl.punchToNormaDevices.length) {

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

            }
            // step3
            else {
              punchToData = $scope.volumeControl.punchToNormaDevices;
              jsonData = JSON.stringify( { punchFrom : punchFrom.id, punchTo : punchToData });

              var url;
              if ($rootScope.virtualEditor) {
                url = '/api/dealer/device/punch_multi/' + $scope.room.id;
              } else {
                url = '/api/device/punch_multi/' + $scope.room.id;
              }

              // punch 세팅 API 호출
              punch(url, jsonData, true);
            }

          }
          else {
            alert(data.error);
          }
        }).
        error(function() {
          alert("Please try again");
        });
      }
      // step2 가 없고 step3 만 있는 경우
      else {
        punchToData = $scope.volumeControl.punchToNormaDevices;
        jsonData = JSON.stringify( { punchFrom : punchFrom.id, punchTo : punchToData });

        var url;
        if ($rootScope.virtualEditor) {
          url = '/api/dealer/device/punch_multi/' + $scope.room.id;
        } else {
          url = '/api/device/punch_multi/' + $scope.room.id;
        }

        // punch 세팅 API 호출
        punch(url, jsonData, true);
      }
    }

  };
  
});