'use strict';

var angular = require('angular'),
  _ = require('jsUtil');
require('../modules');

angular
  .module('infoDisplay.directives')
  .directive('sinoInfoListPage', sinoInfoListPage)
  .controller('SinoInfoListPageCtrl', SinoInfoListPageCtrl);

/** @ngInject */
function sinoInfoListPage() {

  return {
    restrict: 'A',
    controller: 'SinoInfoListPageCtrl',
    controllerAs: 'sinoInfoListPageCtrl'
  }
}

/** @ngInject */
function SinoInfoListPageCtrl($scope, ModelService) {
  var self = this;
  self.$scope = $scope;

  self.$scope.selectedItems;
  self.$scope.notSelectedItems;
  self.$scope.selectedIndex = 0;

  self.$scope.refreshItems = refreshItems;
  self.$scope.getSelectedIndex = getSelectedIndex;

  init();

  function init() {

    ModelService.getSelectedModels().then(function(models) {
      $scope.selectedItems = models;
      $scope.selectedItemId = $scope.selectedItems[0].id;
    });

    ModelService.getNotSelectedModel().then(function(models) {
      $scope.notSelectedItems = models;
    });
  }

  $scope.$on('infoModelChange', function(event, selectedItemId, selectedItems) {
      $scope.selectedItemId = selectedItemId;
  });

  function getSelectedIndex(selectedItemId) {
    var selectedIndex;
    _.each($scope.selectedItems, function(selectedItem, key) {
      if (selectedItem && selectedItem.id === selectedItemId) {
        selectedIndex = key;
      }
    });
    return selectedIndex;
  }

  function refreshItems(selectedItems, notSelectedItems) {
    ModelService.setStorageSelectedModel($scope.selectedItems);
    ModelService.setStorageNotSelectedModel($scope.notSelectedItems);
  }
}
