/**
 * Created by shadeeka on 1/22/16.
 */
angular.module('app.controllers')
  .filter('startFrom', function() {
    return function(input, start) {
      start = +start; //parse to int
      if(input)
      return input.slice(start);
      else
      return 0;
    }
  })
  .controller('OperationsCtrl',["$scope","ModalViews","$filter","propertyCache","issuesCache","sparkDataService","auditProtocol", function ($scope,ModalViews,$filter,propertyCache,issuesCache, sparkDataService, auditProtocol) {

    var _self = this;
    _self.viewName ="operations";

    $scope.currentPage = 0;
    $scope.pageSize = 12;
    $scope.data = [];
    $scope.style = propertyCache.day_start.style;

    $scope.getData = function () {
      return $filter('filter')($scope.data, $scope.q);
    }

    $scope.numberOfPages=function(){
      return Math.ceil($scope.getData().length/$scope.pageSize);
    }

    $scope.data=[];

    _self.loadIssues =function(){
      //get issues from local storage if it is there

      //if not show empty message
      issuesCache.loadOperations($scope).then(function(applyScope){
        //here it gets fresh copy everytime
        $scope.data = issuesCache.getOperationsForCurrentStyle();
        applyScope.$safeApply(applyScope);
      }); //this takes time

      issuesCache.loadIssue();
      issuesCache.loadRejects();

    }
    /*---- operation item click handler ----*/
    var selectedOperations =[];
    _self.clickOperation =function(operation){

      var index = selectedOperations.indexOf(operation);
      if (index > -1) {
        selectedOperations.splice(index, 1);
        operation.ischecked = false;
      } else {
        selectedOperations.push(operation);
        operation.ischecked = true;
      }
     //update issue list
      issuesCache.updateOperations($scope.data);
    }

    _self.exit =function(){
      //////////////////audit//////////////////////
      var $audit = auditProtocol.getEvent("addOperations");
      $audit.data.reference.operations = $scope.data;
      sparkDataService.sendDataToServer($audit)
      /////////////////////////////////////////////////

      if(ModalViews.getView(_self.viewName))
        ModalViews.getView(_self.viewName).hide();

    }

    $scope.$on('modal.shown', function (modal) {
      if (ModalViews.getView(_self.viewName).isShown()){
        _self.loadIssues();
        $scope.style = propertyCache.day_start.style;
      }

    });
  }]);
