'use strict';


app.controller('NewRequestController', function ($scope, $state, $modal, toastr, availableModels, categories, Rooms, Requests, Database, WizardHandler) {

  // backspace key 클릭했을 때 Back 버튼 클릭한 것처럼 동작하게 하기
  var backspaceHandler = function(event) {
    if (event.keyCode == 8) {
      event.preventDefault();

      var btns = angular.element('button');

      _.each(btns, function(btn) {
        // 화면에 있는 button 들 중 화면에 보이고 활성화 되어 있는 Back 버튼이 있으면 클릭
        if ($(btn).filter(':visible').filter(':enabled').text() == 'Back') {
          $(btn).click();
        }
      });
    }
  };

  var $doc = angular.element(document);

  $doc.on('keydown', backspaceHandler);

  // backspace key 를 input 에서는 사용해야 하므로 아래와 같이 처리
  $doc.on('focus', 'input', function() {
    $doc.off('keydown', backspaceHandler);
  });
  $doc.on('blur', 'input', function() {
    $doc.on('keydown', backspaceHandler);
  });

  $scope.$on('$destroy', function() {
    $doc.off('keydown', backspaceHandler);
  });


      
  //initialize device
  function initDevice () {
    $scope.brands = null;
    $scope.deviceInfo = null;
    $scope.device = {
      id: uuid.v4(), 
      name: categories[0].device,
      db: { source: 'DB', type: categories[0].name, model: {}},
      target: { type: 1},
      attr: { fav: 0, punch: -1},
      activities: []
    };
  }

  $scope.categories = categories;

  function goTo(wizardName, step) {
    console.log(wizardName, step);
    WizardHandler.wizard(wizardName).goTo(step);
  }

  function resetDeviceWizard() {
    initDevice();
    WizardHandler.wizard('DeviceWizard').goTo(0); 
  }


  initDevice();

  var room = Rooms.generateOne();

  $scope.request = { 
    file: {}, 
    rooms: []
  };

  $scope.request.rooms.push(room);

  $scope.availableModels = availableModels;
  $scope.selection = {room: null};

  $scope.reset = resetDeviceWizard;
  $scope.initDevice = initDevice;
  $scope.goTo = goTo;
  $scope.isEntDevice = Database.checkIfEntertainment;

  $scope.deviceTypes = _.pluck(categories, 'name');

  $scope.finishedWizard = function() {
    
    Requests.submitOne($scope.request).then(function(jobId) {
      console.log(jobId);
      toastr.success('Job request has been submitted!');
      $state.go('home', {reload:true});
    }).catch(toastr.error);
  };


  $scope.showAddDeviceModal = function() {
    $scope.selection.room.devices.push($scope.device);
    var modal = $modal({scope: $scope, title: 'Device Complete!', backdrop: 'static', template: 'views/modal-tpls/add-device.html', show: false});
    modal.$promise.then(modal.show);
  };


  $scope.continue = function() {
    resetDeviceWizard();
    WizardHandler.wizard('RequestWizard').next();
  };

  $scope.fetchBrands = function(type) {
    return Database.retrieveDeviceBrands(type)
            .then(function(data) {
              $scope.brands = _.pluck(data, 'name');
              goTo('DeviceWizard', 1);
              console.log($scope.brands);
            })
            .catch(toastr.error)
            .finally(function() {
              
            });
  };
  
  $scope.fetchDeviceInfo = function(device) {

    return Database.getDeviceInfo(device.db.type, device.db.brand, device.db.model.id, device.target.type, device.db.model.type)
      .then(function(data) {
        console.log(data);
        $scope.deviceInfo = data.attr;
        goTo('DeviceWizard', 3);
      })
      .catch(toastr.error)
      .finally(function() {
        
      });
  };

  
  $scope.currentRequestStep = 'File Info';
  $scope.currentDeviceStep = 'Device Info';
});