/**
 * 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;
          undoEvent.data = _self.lastEvent.jsonSent;

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

            dataPersistenceService.selectStyleSoLiWiseDailyCount(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;
                undoEvent.data.value = (_self.lastEvent.jsonSent.value * -1);
                dataPersistenceService.updateDailyCount(undoEvent);
                $event.data.value = undoEvent.data.value;
                $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;
                undoEvent.data.value = (_self.lastEvent.jsonSent.value * -1);
                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;
                undoEvent.data.value = (_self.lastEvent.jsonSent.value * -1);
                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 = undoEvent.data.value;
                  $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 = undoEvent.data.value;
                    $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;
                undoEvent.data.value = (_self.lastEvent.jsonSent.value * -1);
                dataPersistenceService.updateDailyCount(undoEvent);
                //-------------- data JSON -------------------
                $event.data.value = undoEvent.data.value;
                $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});
                //}
              }

              var line="";
              if(propertyCache.config.lineWithOutStation!=undefined && propertyCache.config.lineWithOutStation!=""){
                line=propertyCache.config.lineWithOutStation;
              }else{
                line=propertyCache.config.line;
              }

              var eventToSendSummery = new Object();
              eventToSendSummery.line_id= line;
              eventToSendSummery.style= propertyCache.day_start.style;
              eventToSendSummery.po= propertyCache.day_start.key2;
              eventToSendSummery.color= propertyCache.day_start.key1;
              eventToSendSummery.station=propertyCache.config.lineWithStation.split(propertyCache.lineSeparator)[1];
              eventToSendSummery.hour=dataPersistenceService.getHourByEpoch(undoEvent.data.datetime);
              eventToSendSummery.epoch=undoEvent.data.datetime;

              if(undoEvent.name == "ftt"){
                eventToSendSummery.fttPcs=-(undoEvent.data.value);
                eventToSendSummery.defectPcs=0;
                eventToSendSummery.defectivePcs=0;
                eventToSendSummery.rectifiedPcs=0;
                eventToSendSummery.rejectPcs=0;
                eventToSendSummery.defectIssue="";
                eventToSendSummery.defectOperation="";
              }else if(undoEvent.name == "defects"){
                eventToSendSummery.fttPcs=0;
                eventToSendSummery.defectPcs=-(undoEvent.data.issues[0].locations.length);
                eventToSendSummery.defectivePcs=-(undoEvent.data.value);
                eventToSendSummery.rectifiedPcs=0;
                eventToSendSummery.rejectPcs=0;
                var issues=undoEvent.data.issues;
                var operation;
                var issueArr=[];
                for(var x in issues){
                  issueArr.push(issues[x].name);
                  operation=issues[x].operations[0];
                }
                eventToSendSummery.defectIssue=JSON.stringify(issueArr);
                eventToSendSummery.defectOperation=operation;

              }else if(undoEvent.name == "rwtogood"){
                eventToSendSummery.fttPcs=0;
                eventToSendSummery.defectPcs=0;
                eventToSendSummery.defectivePcs=0;
                eventToSendSummery.rectifiedPcs=-(undoEvent.data.value);
                eventToSendSummery.rejectPcs=0;
                eventToSendSummery.defectIssue="";
                eventToSendSummery.defectOperation="";
              }else if(undoEvent.name == "reject"){
                eventToSendSummery.fttPcs=0;
                eventToSendSummery.defectPcs=0;
                eventToSendSummery.defectivePcs=0;
                eventToSendSummery.rectifiedPcs=0;
                eventToSendSummery.rejectPcs=-(undoEvent.data.value);
                eventToSendSummery.defectIssue="";
                eventToSendSummery.defectOperation="";
              }
              dataPersistenceService.insertSummery(eventToSendSummery);

            });

          }else {

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

              var line="";
              if(propertyCache.config.lineWithOutStation!=undefined && propertyCache.config.lineWithOutStation!=""){
                line=propertyCache.config.lineWithOutStation;
              }else{
                line=propertyCache.config.line;
              }

              var eventToSendSummery = new Object();
              eventToSendSummery.line_id= line;
              eventToSendSummery.style= propertyCache.day_start.style;
              eventToSendSummery.po= propertyCache.day_start.key2;
              eventToSendSummery.color= propertyCache.day_start.key1;
              eventToSendSummery.station=propertyCache.config.lineWithStation.split(propertyCache.lineSeparator)[1];
              eventToSendSummery.hour=dataPersistenceService.getHourByEpoch(undoEvent.data.datetime);
              eventToSendSummery.epoch=undoEvent.data.datetime;

              if(undoEvent.name == "ftt"){
                eventToSendSummery.fttPcs=-(undoEvent.data.value);
                eventToSendSummery.defectPcs=0;
                eventToSendSummery.defectivePcs=0;
                eventToSendSummery.rectifiedPcs=0;
                eventToSendSummery.rejectPcs=0;
                eventToSendSummery.defectIssue="";
                eventToSendSummery.defectOperation="";
              }else if(undoEvent.name == "defects"){
                eventToSendSummery.fttPcs=0;
                eventToSendSummery.defectPcs=-(undoEvent.data.issues[0].locations.length);
                eventToSendSummery.defectivePcs=-(undoEvent.data.value);
                eventToSendSummery.rectifiedPcs=0;
                eventToSendSummery.rejectPcs=0;
                var issues=undoEvent.data.issues;
                var operation;
                var issueArr=[];
                for(var x in issues){
                  issueArr.push(issues[x].name);
                  operation=issues[x].operations[0];
                }
                eventToSendSummery.defectIssue=JSON.stringify(issueArr);
                eventToSendSummery.defectOperation=operation;

              }else if(undoEvent.name == "rwtogood"){
                eventToSendSummery.fttPcs=0;
                eventToSendSummery.defectPcs=0;
                eventToSendSummery.defectivePcs=0;
                eventToSendSummery.rectifiedPcs=-(undoEvent.data.value);
                eventToSendSummery.rejectPcs=0;
                eventToSendSummery.defectIssue="";
                eventToSendSummery.defectOperation="";
              }else if(undoEvent.name == "reject"){
                eventToSendSummery.fttPcs=0;
                eventToSendSummery.defectPcs=0;
                eventToSendSummery.defectivePcs=0;
                eventToSendSummery.rectifiedPcs=0;
                eventToSendSummery.rejectPcs=-(undoEvent.data.value);
                eventToSendSummery.defectIssue="";
                eventToSendSummery.defectOperation="";
              }
              dataPersistenceService.insertSummery(eventToSendSummery);

            });

          }


          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");
      }

    };
  }]);
