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

  };
});
