/**
 * Created by shadeeka on 12/4/15.
 */
angular.module('app.services')
// =========================================================================
// Undo Operation Service
// =========================================================================
  .factory('undoOperation', ['$log', '$timeout', '$q', '$http', 'dataPersistenceService', 'sparkDataService', 'eventProtocol', '$rootScope', 'propertyCache', 'auditProtocol', function ($log, $timeout, $q, $http, dataPersistenceService, sparkDataService, eventProtocol, $rootScope, propertyCache, auditProtocol) {

    var undoAvailable = false;

    return {
      lastEvent: {},
      //save to server
      put: function (data) {
        $log.debug("undoOperation : put", data);
      },

      //get data from server
      clear: function () {

        var _self = this;
        console.log("Setting last event ---------->", undoAvailable);
        $log.debug("undoOperation : clear");

        if (undoAvailable) {
          var undoEvent = new Object();
          undoEvent.name = _self.lastEvent.dataType;
          dataPersistenceService.selectDailyCount(undoEvent).then(function (result) {


            if (_self.lastEvent.dataType != 'defects' && _self.lastEvent.dataType != 'rwtogood' && _self.lastEvent.dataType != 'reject') {
              var $event = eventProtocol.getEvent(_self.lastEvent.dataType);
              var $audit = auditProtocol.getEvent(_self.lastEvent.dataType);
              //-------------- data JSON -------------------
              console.log("REsult undo ....> " + result.rows.item(0).Type + " " + result.rows.item(0).Count);
              var count = result.rows.item(0).Count;
              count -= _self.lastEvent.jsonSent.value;
              undoEvent.count = count;
              dataPersistenceService.updateDailyCount(undoEvent);
              $event.data.value = (_self.lastEvent.jsonSent.value * -1);
              $event.data.buyerId = _self.lastEvent.jsonSent.buyerId;
              $event.data.categoryId = _self.lastEvent.jsonSent.categoryId;
              $event.data.sizeId = _self.lastEvent.jsonSent.sizeId;
              sparkDataService.sendDataToServer($event);
              // $rootScope.$broadcast("undo-event", _self.lastEvent.dataType);
              $rootScope.$broadcast("undo-event", {type: _self.lastEvent.dataType , value : $event.data.value});

              //////////////////audit//////////////////////
              //$audit.data.reference=$event.data;
              $audit.data.reference.isUndo = true
              sparkDataService.sendDataToServer($audit)
              /////////////////////////////////////////////////
            }

            else if (_self.lastEvent.dataType == 'defects') {
              var $event = eventProtocol.getEvent(_self.lastEvent.dataType);
              var $audit = auditProtocol.getEvent(_self.lastEvent.dataType);
              console.log("REsult undo ....> " + result.rows.item(0).Type + " " + result.rows.item(0).Count);
              var count = result.rows.item(0).Count;
              count -= _self.lastEvent.defectList.length;
              undoEvent.count = count;
              dataPersistenceService.updateDailyCount(undoEvent);
              //-------------- data JSON Modification-------------------
              $event.data.value = -1;
              $event.data.issues = _self.lastEvent.jsonSent.issues;
              //-------------- data JSON Modification--------------------
              console.log("Defect List -_> ", _self.lastEvent.defectList);
              //for (var i = 0; i < _self.lastEvent.defectList.length; i++) {
              var removeDefectList = new Object();
              removeDefectList.id = _self.lastEvent.defectList.id;
              removeDefectList.name = _self.lastEvent.defectList;
              dataPersistenceService.removeUndoDefectCategories(removeDefectList);
              // $rootScope.$broadcast("undo-event", _self.lastEvent.dataType);
              $rootScope.$broadcast("undo-event", {type: _self.lastEvent.dataType , value : $event.data.value});
              //}
              sparkDataService.sendDataToServer($event);

              //////////////////audit//////////////////////
              $audit.data.reference.issues = $event.data.issues;
              $audit.data.reference.isUndo = true
              sparkDataService.sendDataToServer($audit)
              /////////////////////////////////////////////////
            }

            else if (_self.lastEvent.dataType == 'rwtogood') {


              console.log("REsult undo ....> " + result.rows.item(0).Type + " " + result.rows.item(0).Count);
              var count = result.rows.item(0).Count;
              count -= _self.lastEvent.jsonSent.value;
              undoEvent.count = count;
              dataPersistenceService.updateDailyCount(undoEvent);

              if (configData.rwtogoodRectificationSteps == "false") {
                var $event = eventProtocol.getEvent(_self.lastEvent.dataType);
                var $audit = auditProtocol.getEvent(_self.lastEvent.dataType);
                //-------------- data JSON -------------------
                $event.data.value = (_self.lastEvent.jsonSent.value * -1);
                $event.data.categories;
                $event.data.buyerId = _self.lastEvent.jsonSent.buyerId;
                $event.data.categoryId = _self.lastEvent.jsonSent.categoryId;
                $event.data.sizeId = _self.lastEvent.jsonSent.sizeId;
                // $event.data.
                //-------------- data JSON --------------------
                sparkDataService.sendDataToServer($event);
                //////////////////audit//////////////////////
                $audit.data.reference.categories = $event.data.categories;

                $audit.data.reference.isUndo = true
                sparkDataService.sendDataToServer($audit)

                $rootScope.$broadcast("undo-event", {type: _self.lastEvent.dataType , value : $event.data.value});
              } else {
                for (var i = 0; i < _self.lastEvent.categories.length; i++) {
                  var $event = eventProtocol.getEvent(_self.lastEvent.dataType);
                  var $audit = auditProtocol.getEvent(_self.lastEvent.dataType);
                  //-------------- data JSON -------------------
                  $event.data.value = (_self.lastEvent.jsonSent.value * -1);
                  $event.data.categories.push(_self.lastEvent.categories[i].name);
                  //-------------- data JSON --------------------

                  var undoRework = new Object();
                  undoRework.date = sparkDataService.getFormattedDate();
                  undoRework.defect = _self.lastEvent.categories[i].name;
                  dataPersistenceService.insertDefectCategory(undoRework);
                  //dataPersistenceService.updateDefectCategory(undoRework);
                  sparkDataService.sendDataToServer($event);

                  // $rootScope.$broadcast("undo-event", _self.lastEvent.dataType);
                  $rootScope.$broadcast("undo-event", {type: _self.lastEvent.dataType , value : $event.data.value});
                  //////////////////audit//////////////////////
                  $audit.data.reference.categories = $event.data.categories;

                  $audit.data.reference.isUndo = true
                  sparkDataService.sendDataToServer($audit)
                }
              }

            }
            else if (_self.lastEvent.dataType == 'reject') {
              //for (var i = 0; i < _self.lastEvent.categories.length; i++) {
              var $event = eventProtocol.getEvent(_self.lastEvent.dataType);
              var $audit = auditProtocol.getEvent(_self.lastEvent.dataType);

              console.log("REsult undo ....> " + result.rows.item(0).Type + " " + result.rows.item(0).Count);
              var count = result.rows.item(0).Count;
              count -= _self.lastEvent.jsonSent.value;
              undoEvent.count = count;
              dataPersistenceService.updateDailyCount(undoEvent);
              //-------------- data JSON -------------------
              $event.data.value = (_self.lastEvent.jsonSent.value * -1);
              $event.data.rejectreason = _self.lastEvent.categories;
              sparkDataService.sendDataToServer($event);

              //////////////////audit//////////////////////
              $audit.data.reference.rejectreason = $event.data.rejectreason;
              $audit.data.reference.isUndo = true;
              $audit.data.reference.value = (_self.lastEvent.jsonSent.value * -1);
              sparkDataService.sendDataToServer($audit)
              /////////////////////////////////////////////////

              $rootScope.$broadcast("undo-event", {type: _self.lastEvent.dataType , value : $event.data.value});
              //}
            }
          });
          undoAvailable = false;
        }

      },

      setLastEvent: function (event) {
        var _self = this;
        _self.lastEvent = event;
        undoAvailable = true;
        console.log("Setting last event within setter ---------->", undoAvailable);
      },
      setLastAudit: function (event) {
        var _self = this;
        _self.lastAudit = event;
        console.log("Setting last audit even");
      }

    };
  }]);
