/**
 * Created by shadeeka on 12/13/15.
 */
angular.module('app.controllers')
  .controller('ReworkCtrl', function ($scope, $controller, $log, $rootScope, $filter, $state,
                                      dataPersistenceService, sparkDataService, eventProtocol, undoOperation, propertyCache, auditProtocol) {

    var _self = this;
    _self.reworkItems = [];
    _self.title="-";


    _self.prepareRework = function () {

      if(configData.factoryType=="type2"){//intimo
        _self.title = 'Regood';
      }else {
        _self.title = 'Rework';
      }

      if(propertyCache.factoryConfigs.show_style_info_bar == "true"){

        dataPersistenceService.selectStyleSoLiWiseDefectCategories(propertyCache.day_start.style , propertyCache.day_start.key2 , propertyCache.day_start.key1).then(function (result) {

          _self.reworkItems = [];
          if (result.rows.length > 0) {
            for (var j = 0; j < result.rows.length; j++) {
              var defect = new Object();
              defect.id = result.rows.item(j).Id;
              defect.name = result.rows.item(j).Defect;
              if(defect.name != ""){
                _self.reworkItems.push(defect);
              }
              $log.debug(_self.reworkItems);
            }
            var end = new Date().getTime();
          }
        }, function () {
          $log.debug("Error occurred while getting reworks");
        });

      }else {

        dataPersistenceService.selectDefectCategories().then(function (result) {
          _self.reworkItems = [];
          if (result.rows.length > 0) {
            for (var j = 0; j < result.rows.length; j++) {
              var defect = new Object();
              defect.id = result.rows.item(j).Id;
              defect.name = result.rows.item(j).Defect;
              _self.reworkItems.push(defect);
              $log.debug(_self.reworkItems);
            }
            var end = new Date().getTime();
          }
        }, function () {
          $log.debug("Error occurred while getting reworks");
        });

      }

    }

    _self.click = function () {

      $log.debug("Save rework items...");

      if (_self.reworkItems.length > 0) {

        //get selected items
        var selectedList = [];
        selectedList = $filter('filter')(_self.reworkItems, {checked: true});

        if (selectedList.length > 0) {
          for (var i = 0; i < selectedList.length; i++) {

            var $event = eventProtocol.getEvent('rwtogood');
            $log.debug("Return event -> eventProtocol  :", $event);

            var selectedReworkCategories = [];

            var dataObj = new Object();
            dataObj.id = selectedList[i].id;
            dataObj.name = selectedList[i].name;
            dataObj.style = $event.data.style;
            dataObj.so = $event.data.so;
            dataObj.li = $event.data.li;
            selectedReworkCategories.push(selectedList[i].name);

            if(propertyCache.factoryConfigs.show_style_info_bar == "true"){
              dataPersistenceService.removeStyleSoLiWiseDefectCategories(dataObj);
            }else {
              dataPersistenceService.removeDefectCategories(dataObj);
            }

            $event.data.categories = selectedReworkCategories;

            //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)
            }

            sparkDataService.sendDataToServer($event);

            ///////////////////audit//////////////////////
            var $audit = auditProtocol.getEvent('rwtogood');
            $audit.data.reference.categories = selectedReworkCategories;
            sparkDataService.sendDataToServer($audit)
            /////////////////////////////////////////////////

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

          }

          var dataToUndoService = new Object();
          dataToUndoService.dataType = 'rwtogood';
          dataToUndoService.jsonSent = $event.data;
          dataToUndoService.categories= selectedList;
          undoOperation.setLastEvent(dataToUndoService);

        }

      }
      $state.go('app.home');
    }

    //----------- Load rework items before view enter ----//

    $scope.$on('$ionicView.beforeEnter', function () {
      $scope.$parent.clearAllFabs();
      _self.prepareRework();
    });

    $scope.$on('$ionicView.leave', function () {
      _self.reworkItems = [];
    });
  });
