/**
 * Created by shadeeka on 1/24/16.
 */
angular.module('app.controllers')
  .controller('OpsRejectsCtrl', ["$scope", "$log", "issuesCache", "$ionicSlideBoxDelegate", "eventProtocol", "$state", "propertyCache", "ModalViews", "cacheViews", "$rootScope", "dataPersistenceService", "sparkDataService", "undoOperation", "$ionicHistory","auditProtocol","$translate",
    function ($scope, $log, issuesCache, $ionicSlideBoxDelegate, eventProtocol, $state, propertyCache, ModalViews, cacheViews, $rootScope, dataPersistenceService, sparkDataService, undoOperation, $ionicHistory, auditProtocol,$translate) {

      var _self = this;
      _self.currentRejects = []; //issues for selected operation

      _self.rejectslist = [];//final issue list to save
      _self.lastIndex = 1;
      $scope.currentPage = 0;
      $scope.currentPagei = 0;
      $scope.pageSize = 14;
      $scope.isSingleSelectRejects = false;
      $scope.isEnglish=true;

      _self.selectedRejects = [];
      $scope.style = propertyCache.day_start.style;

      _self.rejectClick = function (reject) {

        if ($scope.isSingleSelectRejects) {

        } else {
          _self.handleMultiSelectRejects(reject);
        }
      }

      _self.resetState = function () {
        _self.selectedRejects=[];
        _self.currentRejects = cacheViews.rejectsToRender;
        _self.rejectslist = cacheViews.rejectListToSave;

        angular.forEach(_self.currentRejects, function (op, index) {
          _self.currentRejects[index].ischecked = false;
        });
        cacheViews.toRejects = -1;
        $scope.$safeApply($scope);
      }
      var selectedReject = {};

      _self.handleSingleSelectRejects = function (reject) {
        selectedReject.ischecked = false;
        selectedReject = reject;
        reject.ischecked = true;
      }
      _self.handleMultiSelectRejects = function (reject) {
        var index = _self.selectedRejects.indexOf(reject);
        if (index > -1) {
          _self.selectedRejects.splice(index, 1);
          reject.ischecked = false;
        } else {
          _self.selectedRejects.push(reject);
          reject.ischecked = true;
        }

        _self.updateRejects(_self.selectedRejects);
      }

      _self.saveFinalList = function (reject) {

        if (!reject.hasOwnProperty('name'))
          return;

        //this is a new issue
        var newReject = angular.copy(reject);

        newReject.rejects = _self.selectedRejects;
        _self.lastIndex = _self.rejectslist.push(newReject);

        $log.debug(">> added to final list :", _self.rejectslist);

      }
      _self.isInList = function (list, newReject) {
        var ret = {};
        angular.forEach(list, function (reject, index) {
          if (newReject.category_id == reject.category_id) {
            ret.index = index;
            ret.reject = reject;
          }
        });
        return ret;
      }

      _self.transformIntoStandard = function (operationsList) {
        var list = angular.copy(operationsList);
        var rejectList = [];
        angular.forEach(list, function (opp, index) {
          angular.forEach(opp.rejects, function (reject, idx) {

            var newReject = new Object();
            newReject.category_id = reject.category_id;
            newReject.name = reject.name;
            newReject.operation = [opp.name];

            var indexItm = _self.isInList(rejectList, newReject);

            if (angular.isDefined(indexItm.index))
              rejectList[indexItm.index].operation.push(opp.name);
            else
              rejectList.push(newReject);
          });
        });

        return rejectList;
      }

      _self.save = function () {

        var $event = eventProtocol.getEvent('reject');
        var rejects = [];
        rejects = _self.transformIntoStandard(_self.rejectslist);
        $event.data.rejectreason = rejects;


        if (rejects[rejects.length - 1].operation.length > 0) {

          $rootScope.$broadcast("modelCountUpdate", {type: "reject"});

         //send event to database
          //dataPersistenceService.dailyCountPreProcess($event);


          if(propertyCache.factoryConfigs.show_style_info_bar == "true") {
            dataPersistenceService.selectStyleSoLiWiseDailyCount($event).then(function (res) {
              dataPersistenceService.updateDailyCount($event);
            }, function (err) {
              dataPersistenceService.insertDailyCount($event);
            });
          }else{
            dataPersistenceService.dailyCountPreProcess($event)
          }
//////////////////////

         //set undo operation
          var dataToUndoService = new Object();
          dataToUndoService.dataType = 'reject';
          dataToUndoService.jsonSent = $event.data;
          dataToUndoService.categories= rejects;

          undoOperation.setLastEvent(dataToUndoService);

           //send data to remote server
          sparkDataService.sendDataToServer($event);

          ///////////////////audit//////////////////////
          var $audit = auditProtocol.getEvent('reject');
          $audit.data.reference.rejectreason = rejects;
          sparkDataService.sendDataToServer($audit)
          /////////////////////////////////////////////////

          $ionicHistory.nextViewOptions({
                  disableBack: true
                });
          $state.go('app.home');
        } else {

        }
      }


      _self.updateRejects = function (operations) {
        //override existing
        _self.rejectslist[_self.lastIndex - 1].rejects = operations;
        $log.debug(">> updated list :", _self.rejectslist);
      }

      $scope.numberOfPages = function (array) {
        return Math.ceil(array.length / $scope.pageSize);
      }
      $scope.$on('$ionicView.beforeEnter', function () {
        $scope.$parent.clearAllFabs();
        if (cacheViews.toRejects === 0) {
          _self.resetState();
        }

        var usedLanguage=$translate.use();
        if(usedLanguage!= undefined && usedLanguage!=""){
          if(usedLanguage!="en"){
            $scope.isEnglish=false;
          }else{
            $scope.isEnglish=true;
          }
        }
      });
    }]);
