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

    this.cache;

    var currentDate = "";

    return {

      sendDataToServer: function (event) {

        if(propertyCache.factoryConfigs.count_track_mac_address!=undefined && propertyCache.factoryConfigs.count_track_mac_address) {
          if (event.name == "ftt" || event.name == "defects" || event.name == "rwtogood" || event.name == "reject" || event.name == "styles" || event.name == "members" || event.name == "operations") {
              //setting up mac address
              event.data.macAddress = propertyCache.macAddress;
          }
        }



        var dataapipr = this.save(event);
        dataapipr.then(function (result) {
          console.log("Success Result ---> " + result);
          if (result.status != '201' && result.statusText != 'Created') {
            console.log("Inserted into Network Faliure even if Success ! " + result.status + " " + result.statusText);
            event.status='PENDING';
            dataPersistenceService.insertNetworkFailureData(event);

            var netdatapr = dataPersistenceService.selectNetworkFaliure();
            netdatapr.then(function (result) {
              console.log("Data Row Count ----> " + result.rows.length);
              /*for (var i = 0; i < result.rows.length; i++) {
                console.log(result.rows.item(i).Date + " " + result.rows.item(i).Type + " " + result.rows.item(i).Data);
              }*/

            })
          }
        }, function (result) {
          //console.log("Error Result---> " + result);
          //console.log("Inserted into Network Faliure When Result Failure !");
          event.status='PENDING';
          dataPersistenceService.insertNetworkFailureData(event);
          var netdatapr = dataPersistenceService.selectNetworkFaliure();
          netdatapr.then(function (result) {
            console.log("Data Row Count ----> " + result.rows.length);
            /*for (i = 0; i < result.rows.length; i++) {
              $log.debug(result.rows.item(i).Date + " " + result.rows.item(i).Type + " " + result.rows.item(i).Data);
            }*/

          })
        });
      },

      //send to server
      save: function (eventData) {
        var deferred = $q.defer();
        $log.debug("sparkDataService : save");
        var self = this;
        //$log.debug("Json data ---> " + eventData.data);
        //$log.debug("Cache ---> ", propertyCache.config);
        $http.post('http://' + propertyCache.config.dataIp + '/' + eventData.endPoint + '/' + eventData.name, eventData.data).then(function (resp) {
          // $log.debug('Success', resp);
          deferred.resolve(resp);
        }, function (err) {
          $log.debug('ERR', err);
          deferred.reject(err);
        })

        return deferred.promise;
      },

      //send to server
      syncSendRecords: function (eventData) {
        var deferred = $q.defer();
        $log.debug("sparkDataService : save");
        var self = this;
        //$log.debug("Cache ---> ", propertyCache.config);
        $http.post('http://' + propertyCache.config.dataIp + '/' + eventData.endPoint + '/' + eventData.name, eventData.data).then(function (resp) {
          //$log.debug('Success', resp);
          deferred.resolve(eventData);
        }, function (err) {
          $log.debug('ERR', err);
          deferred.reject(eventData);
        })

        return deferred.promise;
      },

      syncAuthentication: function () {
        var deferred = $q.defer();
        if (localStorage.getItem("isAuthenicationAvailable") == undefined) {
          localStorage.setItem("isAuthenicationAvailable", false)
        }
        if ((localStorage.getItem("isAuthenicationAvailable") == "false")) {


          $log.debug("sparkDataService : Sync Authentication");

          var self = this;

          $log.debug("Property cache --> ", propertyCache.config);

          $http.get('http://' + propertyCache.config.syncIp + '/dataman/getprofiles?role=qc-user&tenant=' + propertyCache.config.tenant + '&factory=' + propertyCache.config.factory).then(function (response) {
            $log.debug("Sync Auth response----> " + response);
            dataPersistenceService.removeAllAuthentication().then(function (result) {
              var dbUsers = response['data'];
              localStorage.setItem("isAuthenicationAvailable", true)
              angular.forEach(dbUsers, function (dbUser, key) {
                var user = new Object();
                user.username = dbUser['username'];
                user.password = dbUser['password'];
                dataPersistenceService.saveAuthentication(user);
              })
            });
            deferred.resolve(response);

          }, function (err) {
            $log.debug('ERR', err);
            deferred.reject(err);
          });

        }
        return deferred.promise;
      },

      getSessionPlans: function () {
        var deferred = $q.defer();

        $log.debug("sparkDataService : Sync Session Plans");

        var self = this;
        var line="";
        if(propertyCache.config.lineWithOutStation!=undefined && propertyCache.config.lineWithOutStation!=""){
          line=propertyCache.config.lineWithOutStation;
        }else{
          line=propertyCache.config.line;
        }
        $http.get('http://' + propertyCache.config.syncIp + '/dataman/plannames?factory=' + propertyCache.config.factory + '&module=' + line + '&tenant=' + propertyCache.config.tenant).then(function (response) {
          var home = response['data'];
          angular.forEach(home, function (object, key) {
            var plns = object.plans;
            for (var i = 0; i < plns.length; i++) {
              var data = new Object();
              data.name = plns[i];
              data.time = "";
              dataPersistenceService.saveSessionPlanNames(data).then(function (result) {
                dataPersistenceService.selectSessionPlanNames().then(function (res) {
                  self.sessionsPlans = [];
                  for (var i = 0; i < res.rows.length; i++) {
                    self.sessionsPlans.push(res.rows.item(i).Name);
                  }
                  propertyCache.plans.sessionsPlans = self.sessionsPlans;
                });
              });
            }
          })

          deferred.resolve(response);
        }, function (err) {
          $log.debug('ERR', err);
          deferred.reject(err);
        })
        return deferred.promise;
      },

      tabChangeSync: function () {
        var _self = this;
        var deferred = $q.defer();
        this.syncDailyCounts().then(function (result) {
          deferred.resolve(result);
          $log.debug("Success Sync ", result);
        }, function (err) {
          deferred.reject(err);
          $log.debug("Err0r Sync ", err);
        });


        return deferred.promise;
      },

      syncDailyCounts: function () {
        $log.debug("calling the syncDailyCounts !");
        var self = this;

        var deferred = $q.defer();
        var macAdd="";
        if(propertyCache.factoryConfigs.count_track_mac_address!=undefined && propertyCache.factoryConfigs.count_track_mac_address) {
          macAdd=propertyCache.macAddress;
        }

        var url = "";
        if(propertyCache.factoryConfigs.show_style_info_bar == "true"){
          url = 'http://' + propertyCache.config.syncIp + '/dataman/synchronize?date=' + self.getFormattedDate() + '&factory=' + propertyCache.config.factory + '&line=' + propertyCache.config.line + '&tenant=' + propertyCache.config.tenant+'&macAddress='+macAdd +'&stylewise='+ true;
        }else {
          url = 'http://' + propertyCache.config.syncIp + '/dataman/synchronize?date=' + self.getFormattedDate() + '&factory=' + propertyCache.config.factory + '&line=' + propertyCache.config.line + '&tenant=' + propertyCache.config.tenant+'&macAddress='+macAdd +'&stylewise='+ false;
        }

        $http.get(url).then(function (response) {

          // have to refactor

          $log.debug("calling the sync !");

          var val = response['data'];

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

            if(val.fttCount != null)
            for(var i =0 ; i < val.fttCount.length ; i ++){
              var obj = val.fttCount[i];

              var event = new Object();
              event.date = self.getFormattedDate();
              event.name = 'ftt';
              event.data = {};
              event.data.style = obj.style;
              event.data.so = obj.so;
              event.data.li = obj.li;
              event.data.value = obj.fttCount;
              event.count = obj.fttCount;
              dataPersistenceService.syncStyleSoLiWiseCountPreProcess(event);

            }

            if(val.defectCount != null)
            for(var i =0 ; i < val.defectCount.length ; i ++){
              var obj = val.defectCount[i];

              var event = new Object();
              event.date = self.getFormattedDate();
              event.name = 'defects';
              event.data = {};
              event.data.style = obj.style;
              event.data.so = obj.so;
              event.data.li = obj.li;
              event.data.value = obj.defectCount;
              event.count = obj.defectCount;
              dataPersistenceService.syncStyleSoLiWiseCountPreProcess(event);

            }

            if(val.reworkCount != null)
            for(var i =0 ; i < val.reworkCount.length ; i ++){
              var obj = val.reworkCount[i];

              var event = new Object();
              event.date = self.getFormattedDate();
              event.name = 'rwtogood';
              event.data = {};
              event.data.style = obj.style;
              event.data.so = obj.so;
              event.data.li = obj.li;
              event.data.value = obj.reworkCount;
              event.count = obj.reworkCount;
              dataPersistenceService.syncStyleSoLiWiseCountPreProcess(event);

            }

            if(val.rejectCount != null)
            for(var i =0 ; i < val.rejectCount.length ; i ++){
              var obj = val.rejectCount[i];

              var event = new Object();
              event.date = self.getFormattedDate();
              event.name = 'reject';
              event.data = {};
              event.data.style = obj.style;
              event.data.so = obj.so;
              event.data.li = obj.li;
              event.data.value = obj.rejectCount;
              event.count = obj.rejectCount;
              dataPersistenceService.syncStyleSoLiWiseCountPreProcess(event);

            }

          }else {

            var event = new Object();
            event.date = self.getFormattedDate();
            event.name = 'ftt';
            event.count = val['fttCount'];
            event.data = {};
            event.data.style = "";
            event.data.so = "";
            event.data.li = "";
            event.data.value = val['fttCount'];
            dataPersistenceService.syncCountPreProcess(data);

            var event = new Object();
            event.date = self.getFormattedDate();
            event.name = 'defects';
            event.count = val['defectCount'];
            event.data = {};
            event.data.style = "";
            event.data.so = "";
            event.data.li = "";
            event.data.value = val['defectCount'];
            dataPersistenceService.syncCountPreProcess(event);

            var event = new Object();
            event.name = 'rwtogood';
            event.date = self.getFormattedDate();
            event.count = val['reworkCount'];
            event.data = {};
            event.data.style = "";
            event.data.so = "";
            event.data.li = "";
            event.data.value = val['reworkCount'];
            dataPersistenceService.syncCountPreProcess(event);

            var event = new Object();
            event.name = 'reject';
            event.count = val['rejectCount'];
            event.date = self.getFormattedDate();
            event.data = {};
            event.data.style = "";
            event.data.so = "";
            event.data.li = "";
            event.data.value = val['rejectCount'];
            dataPersistenceService.syncCountPreProcess(event);

          }

          ///////// day start data synchronization /////////////////////////

          var data = new Object();
          data.key = 'sessionPlan';
          data.value = val['sessionplanname'];
          data.date = self.getFormattedDate();
          if(data.value != null){
            dataPersistenceService.insertDayStart(data);
          }

          var data = new Object();
          data.key = 'style';
          data.value = val['style'];
          data.date = self.getFormattedDate();
          if(data.value != null){
            dataPersistenceService.insertDayStart(data);
          }

          var data = new Object();
          data.key = 'members';
          data.value = val['members'];
          data.date = self.getFormattedDate();
          if(data.value != null){
            dataPersistenceService.insertDayStart(data);
          }

          var data = new Object();
          data.key = 'key1';
          data.value = val['key1'];
          data.date = self.getFormattedDate();
          if(data.value != null){
            dataPersistenceService.insertDayStart(data);
          }


          var data = new Object();
          data.key = 'key2';
          data.value = val['key2'];
          data.date = self.getFormattedDate();
          if(data.value != null){
            dataPersistenceService.insertDayStart(data);
          }

          var data = new Object();
          data.key = 'siluhoutteid';
          data.value = val['siluhoutteid'];
          data.date = self.getFormattedDate();
          if(data.value != null){
            dataPersistenceService.insertDayStart(data);
          }

          var data = new Object();
          data.key = 'operators';
          data.value = val['operators'];
          data.date = self.getFormattedDate();
          if(data.value != null){
            dataPersistenceService.insertDayStart(data);
          }

          var data = new Object();
          data.key = 'helpers';
          data.value = val['helpers'];
          data.date = self.getFormattedDate();
          if(data.value != null){
            dataPersistenceService.insertDayStart(data);
          }

          var data = new Object();
          data.key = 'categoryId';
          data.value = val['categoryId'];
          data.date = self.getFormattedDate();
          if(data.value != null){
            dataPersistenceService.insertDayStart(data);
          }

          var data = new Object();
          data.key = 'buyerId';
          data.value = val['buyerId'];
          data.date = self.getFormattedDate();
          if(data.value != null){
            dataPersistenceService.insertDayStart(data);
          }

          var data = new Object();
          data.key = 'sizeId';
          data.value = val['sizeId'];
          data.date = self.getFormattedDate();
          if(data.value != null){
            dataPersistenceService.insertDayStart(data);
          }

          if (val['style'] != null && val['style'] != undefined) {
            propertyCache.updateDayStartStyle(val['style']);
          }

          //////////////////////////////////////////////////////////

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

          deferred.resolve(response);
          //dataPersistenceService.saveAuthentication();
        }, function (err) {
          $log.debug('ERR', err);
          deferred.reject(err);
        })
        return deferred.promise;
      },

      unreworkedDefectSync: function () {
        var deferred = $q.defer();

        $log.debug("sparkDataService : Sync Session Plans");

        var self = this;

        var macAdd="";
        if(propertyCache.factoryConfigs.count_track_mac_address!=undefined && propertyCache.factoryConfigs.count_track_mac_address) {
          macAdd=propertyCache.macAddress;
        }

        var url = "";
        if(propertyCache.factoryConfigs.show_style_info_bar == "true"){
          url = 'http://' + propertyCache.config.syncIp + '/dataman/unrwkdefects?date=' + self.getFormattedDate() + '&factory=' + propertyCache.config.factory + '&line=' + propertyCache.config.line + '&tenant=' + propertyCache.config.tenant+'&macAddress='+macAdd +'&stylewise='+ true;
        }else {
          url = 'http://' + propertyCache.config.syncIp + '/dataman/unrwkdefects?date=' + self.getFormattedDate() + '&factory=' + propertyCache.config.factory + '&line=' + propertyCache.config.line + '&tenant=' + propertyCache.config.tenant+'&macAddress='+macAdd +'&stylewise='+ false;
        }


        $http.get(url).then(function (response) {
          //$log.debug("Sync Session Plans response----> "+ this.response);


          dataPersistenceService.removeAllDefectCategories().then(function (result) {
            var home = response['data'];


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

              angular.forEach(home, function (object, key) {
                angular.forEach(object , function(ob , styleKey) {
                  var ar = [];
                  ar = styleKey.split("@");
                  var categoryData = new Object();
                  categoryData.date = self.getFormattedDate();
                  categoryData.style = ar[0];
                  categoryData.so = ar[1];
                  categoryData.li = ar[2];

                  for (var i = 0; i < ob.length; i++) {
                    var defects = [];
                    defects.push(ob[i]);
                    categoryData.defect = defects;
                    if(defects.length > 0){
                      dataPersistenceService.insertDefectCategory(categoryData);
                    }
                  }

                })

              })

            }else {
              angular.forEach(home, function (object, key) {
                var categoryData = new Object();
                categoryData.date = self.getFormattedDate();
                var defects = [];
                for (var i = 0; i < object.length; i++) {
                  defects.push(object[i]);
                }
                categoryData.defect = defects;
                dataPersistenceService.insertDefectCategory(categoryData);
              })
            }



          });
          deferred.resolve(response);
          //dataPersistenceService.saveAuthentication();
        }, function (err) {
          $log.debug('ERR', err);
          deferred.reject(err);
        });
        return deferred.promise;
      },


      getSiluhoutteNames: function () {
        var deferred = $q.defer();

        $log.debug("sparkDataService : Siluhoutte Names");

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

        $http.get('http://' + propertyCache.config.syncIp + '/dataman/getsiluhouttes?factory=' + propertyCache.config.factory +
        '&line=' + line + '&tenant=' + propertyCache.config.tenant).then(function (response) {
          $log.debug("Siluhouttes-----------------> ", response);
          var data = response['data'];
          dataPersistenceService.removeSiluhoutte().then(function (response) {
            for (var i = 0; i < data.length; i++) {
              dataPersistenceService.insertSiluhoutte(data[i]).then(function (result) {
                dataPersistenceService.selectSiluhouttes().then(function (result) {
                  self.siluhouttes = [];
                  for (var i = 0; i < result.rows.length; i++) {
                    self.siluhouttes.push(result.rows.item(i).Name);
                  }
                  propertyCache.siluhouttes.silihoutteNames = self.siluhouttes;
                  //$log.debug("Siluhouttes selected from db ------> ", propertyCache.siluhouttes.silihoutteNames);
                })
              })
            }
          }, function (err) {
            for (var i = 0; i < data.length; i++) {
              dataPersistenceService.insertSiluhoutte(data[i]).then(function (result) {
                dataPersistenceService.selectSiluhouttes().then(function (result) {
                  self.siluhouttes = [];
                  for (var i = 0; i < result.rows.length; i++) {
                    self.siluhouttes.push(result.rows.item(i).Name);
                  }
                  propertyCache.siluhouttes.silihoutteNames = self.siluhouttes;
                  //$log.debug("Siluhouttes selected from db ------> ", propertyCache.siluhouttes.silihoutteNames);
                })
              })
            }
          })
          deferred.resolve(response);
        }, function (err) {
          $log.debug('ERR', err);
          deferred.reject(err);
        })

        return deferred.promise;
      },


      getStyles: function () {
        var deferred = $q.defer();

        $log.debug("sparkDataService : Style Names");

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

        $http.get('http://' + propertyCache.config.syncIp + '/dataman/getstylenamesforfivedays?factory=' + propertyCache.config.factory + '&line=' + line +
        '&tenant=' + propertyCache.config.tenant + '&date=' + self.getFormattedCurrentDateDash()).then(function (response) {

          $log.debug("Styles-----------------> ", response);
          var data = [];
          data = response['data'];

          self.styles = [];
          self.pos = [];
          self.colours = [];

          if (data.length) {
            dataPersistenceService.removeStyles_Po_Colour().then(function (response) {
              for (var i = 0; i < data.length; i++) {
                var list = data[i];
                var event = new Object();
                event.style = list[0];
                event.po = list[1];
                event.colour = list[2];

                dataPersistenceService.addStyles_Po_Colour(event).then(function (result) {
                  //dataPersistenceService.selectAllFromStyles_po_colours().then(function (result) {
                  //  self.styles = [];
                  //  self.pos = [];
                  //  self.colours = [];
                  //  //$log.debug("Fetched item from the db ",result.rows);
                  //  for (var i = 0; i < result.rows.length; i++) {
                  //    if($.inArray(result.rows.item(i).Style, self.styles) == -1){
                  //      self.styles.push(result.rows.item(i).Style);
                  //    }
                  //
                  //    if($.inArray(result.rows.item(i).Po, self.pos) == -1){
                  //      self.pos.push(result.rows.item(i).Po);
                  //    }
                  //
                  //    if($.inArray(result.rows.item(i).Colour, self.colours) == -1){
                  //      self.colours.push(result.rows.item(i).Colour);
                  //    }
                  //  }
                  //  propertyCache.planedStyles.styleNames = self.styles;
                  //  propertyCache.pos.poNames = self.pos;
                  //  propertyCache.colours.colorCodes = self.colours;
                  //  $log.debug("Property cache set ---------> ", propertyCache.planedStyles.styleNames);
                  //  $log.debug("Property cache set ---------> ", propertyCache.planedStyles);
                  //
                  //})
                })
              }

              propertyCache.planedStyles.styleNames = self.styles;
              propertyCache.pos.poNames = self.pos;
              propertyCache.colours.colorCodes = self.colours;
              deferred.resolve(response);
            }, function (err) {
              for (var i = 0; i < data.length; i++) {
                var list = data[i];
                var event = new Object();
                event.style = list[0];
                event.po = list[1];
                event.colour = list[2];

                //self.styles.push(list[0]);
                //self.pos.push(list[1]);
                //self.colours.push(list[2]);


                dataPersistenceService.addStyles_Po_Colour(event).then(function (result) {
                  //dataPersistenceService.selectAllFromStyles_po_colours().then(function (result) {
                  //  self.styles = [];
                  //  self.pos = [];
                  //  self.colours = [];
                  //  for (var i = 0; i < result.rows.length; i++) {
                  //    if($.inArray(result.rows.item(i).Style, self.styles) == -1){
                  //      self.styles.push(result.rows.item(i).Style);
                  //    }
                  //
                  //    if($.inArray(result.rows.item(i).Po, self.pos) == -1){
                  //      self.pos.push(result.rows.item(i).Po);
                  //    }
                  //
                  //    if($.inArray(result.rows.item(i).Colour, self.colours) == -1){
                  //      self.colours.push(result.rows.item(i).Colour);
                  //    }
                  //  }
                  //  propertyCache.planedStyles.styleNames = self.styles;
                  //  propertyCache.pos.poNames = self.pos;
                  //  propertyCache.colours.colorCodes = self.colours;
                  //})
                })
              }
                deferred.reject(err);
            }
            )
          }

        }, function (err) {
          $log.debug('Error in getting the Style names ', err);
          deferred.reject(err);
        })

        return deferred.promise;
      },getLineQualityReport: function (line) {
        var self = this;
        console.log("calling getLineQualityReport ");
        var startDate=new Date();
        var deferred = $q.defer();
        var d = new Date();
        var month = '' + (d.getMonth() + 1);
        var day = '' + d.getDate();
        var year = d.getFullYear();
        if (month.length < 2)
          month = '0' + month;
        if (day.length < 2)
          day = '0' + day;
        var currentDate = year + "." + month + "." + day;
        $http.get('http://' + propertyCache.config.syncIp + '/dataman/getLineQualityReport?date=' + currentDate+ '&factory='
        + propertyCache.config.factory + '&line=' + line + '&tenant=' + propertyCache.config.tenant).then(function (response) {
          console.log("Sync Auth response----> " + response);
          dataPersistenceService.removeAllSummery().then(function (result) {
            var summeryData = response['data'];
            if(summeryData.length > 0) {
              for(var i=0;i<summeryData.length;i++) {
                console.debug('summeryData', summeryData[i]);

                var eventToSendSummery = new Object();
                eventToSendSummery.line_id= summeryData[i].line_id;
                eventToSendSummery.style= summeryData[i].style;
                eventToSendSummery.po= summeryData[i].so;
                eventToSendSummery.color= summeryData[i].li;
                eventToSendSummery.station=summeryData[i].station;
                eventToSendSummery.hour=dataPersistenceService.getHourByEpoch(summeryData[i].datetime);
                eventToSendSummery.epoch=summeryData[i].datetime;
                if(summeryData[i].data_type == "ftt"){
                  eventToSendSummery.fttPcs=summeryData[i].value;
                  eventToSendSummery.defectPcs=0;
                  eventToSendSummery.defectivePcs=0;
                  eventToSendSummery.rectifiedPcs=0;
                  eventToSendSummery.rejectPcs=0;
                  eventToSendSummery.defectIssue="";
                  eventToSendSummery.defectOperation="";
                }else if(summeryData[i].data_type == "defects"){
                  eventToSendSummery.fttPcs=0;
                  eventToSendSummery.defectPcs=summeryData[i].defects;
                  eventToSendSummery.defectivePcs=summeryData[i].value;
                  eventToSendSummery.rectifiedPcs=0;
                  eventToSendSummery.rejectPcs=0;
                  var issues=summeryData[i].issues;
                  var operation=summeryData[i].operation;
                  eventToSendSummery.defectIssue=JSON.stringify(issues);
                  eventToSendSummery.defectOperation=operation;
                }else if(summeryData[i].data_type == "rwtogood"){
                  eventToSendSummery.fttPcs=0;
                  eventToSendSummery.defectPcs=0;
                  eventToSendSummery.defectivePcs=0;
                  eventToSendSummery.rectifiedPcs=summeryData[i].value;
                  eventToSendSummery.rejectPcs=0;
                  eventToSendSummery.defectIssue="";
                  eventToSendSummery.defectOperation="";
                }else if(summeryData[i].data_type == "reject"){
                  eventToSendSummery.fttPcs=0;
                  eventToSendSummery.defectPcs=0;
                  eventToSendSummery.defectivePcs=0;
                  eventToSendSummery.rectifiedPcs=0;
                  eventToSendSummery.rejectPcs=summeryData[i].value;
                  eventToSendSummery.defectIssue="";
                  eventToSendSummery.defectOperation="";
                }
                dataPersistenceService.insertSummery(eventToSendSummery);
              }
            }
            deferred.resolve(response);
          });
        }, function (err) {
          console.error('ERR', err);
          deferred.reject(err);
        });
        return deferred.promise;
      },
      loadSessionDetail: function(sessionPlanName) {
      var deferred = $q.defer();
      $log.info("getting loadSessionDetail data from server  ");
      var factory = propertyCache.config.factory;
      var tenant = propertyCache.config.tenant;
      var url = 'http://' + propertyCache.config.syncIp +
        '/dataman/getsessiondetailsinfo?tenant=' + tenant + '&factory=' + factory + '&sessionPlanName=' + sessionPlanName ;
      $http.get(url).then(function (response) {
        console.log("get plan data from server ----> " + response);
        deferred.resolve(response);
        var dataServer = response["data"];
        if (dataServer != "") {
          propertyCache.day_start["sessionPlanDetail"] = angular.extend(dataServer.sessionPlanDetail);
        }
      }, function (err) {
        console.log('ERR', err);
        deferred.reject(err);
      })
    },


      getOperationsForStyles: function (style) {
        var deferred = $q.defer();
        $log.debug("sparkDataService : Siluhoutte Names");

        var self = this;
        if (style == undefined) {
          style = propertyCache.day_start.style;
        }

        $http.get('http://' + propertyCache.config.syncIp + '/dataman/getoperationslist?factory=' + propertyCache.config.factory + '&style=' + style + '&tenant=' + propertyCache.config.tenant).then(function (response) {
          $log.debug("Operations List ", response);
          dataPersistenceService.removeStyleOperation().then(function (res) {
            $log.debug("Removed rows ------> " + res.rows.length);
            var data = response['data'];
            //$log.debug("OPerations Data ----------> ",data);
            for (var i = 0; i < data.length; i++) {
              var op = data[i];
              //$log.debug("OPerstion ----------> ",op);
              var style = "";
              for (var j = 0; j < op.length; j++) {

                if (op[j].style != null) {
                  //$log.debug("OPerstion ----------> ",op[j].style);
                  style = op[j].style;
                } else {
                  //$log.debug("OPerstion ----------> ",op[j]);
                  var eventToSend = new Object();
                  eventToSend.style = style;
                  eventToSend.operation = JSON.stringify(op[j]);

                  dataPersistenceService.insertStyleOperation(eventToSend);
                }
              }
            }
          }, function (err) {

            $log.debug("No OPerations to remove !");
          })
          deferred.resolve(response);
        }, function (err) {
          $log.debug('ERR', err);
          deferred.reject(err);
        })

        return deferred.promise;
      },
      getIssuesList: function () {
        var deferred = $q.defer();
        $log.debug("sparkDataService : getIssuesList");
        var self = this;
        $http.get('http://' + propertyCache.config.syncIp + '/dataman/getissuelist?factory=' + propertyCache.config.factory + '&tenant=' + propertyCache.config.tenant).then(function (response) {
          $log.debug("Issue List ", response);
          dataPersistenceService.removeIssueList().then(function(res){
            $log.debug("Removed rows ------> "+ res.rows.length);
            var data = response['data'];
            var eventToSend = new Object();
            eventToSend.issueName = JSON.stringify(data);
            dataPersistenceService.insertIssue(eventToSend);
          },function(err){
            $log.debug("No Issue list to remove !");
          })
          deferred.resolve(response);
        }, function (err) {
          $log.debug('ERR', err);
          deferred.reject(err);
        })

        return deferred.promise;
      },
      getRejectList: function () {
        var deferred = $q.defer();
        $log.debug("sparkDataService : getRejectList");
        var self = this;
        $http.get('http://' + propertyCache.config.syncIp + '/dataman/getrejectlist?factory=' + propertyCache.config.factory + '&tenant=' + propertyCache.config.tenant).then(function (response) {
          $log.debug("Issue List ", response);
          dataPersistenceService.removeRejectList().then(function(res){
            $log.debug("Removed rows ------> "+ res.rows.length);
            var data = response['data'];
            var eventToSend = new Object();
            eventToSend.rejectName = JSON.stringify(data);
            dataPersistenceService.insertReject(eventToSend);
          },function(err){
            $log.debug("No Reject list to remove !");
          })
          deferred.resolve(response);
        }, function (err) {
          $log.debug('ERR', err);
          deferred.reject(err);
        })

        return deferred.promise;
      },

      getAppConfig: function () {
        var deferred = $q.defer();
        $log.debug("sparkDataService : get app config");
        var self = this;
        $http.get('http://' + propertyCache.config.syncIp + '/dataman/getlineconfig?factory=' + propertyCache.config.factory + '&line=' + propertyCache.config.line + '&tenant=' + propertyCache.config.tenant).then(function (response) {
          deferred.resolve(response);
        }, function (err) {
          $log.debug('ERR', err);
          deferred.reject(err);
        });
        return deferred.promise;
      },

      sendAppConfig: function (pcb, efficiency, quality,notification) {
        var deferred = $q.defer();
        $log.debug("sparkDataService : set app config");
        var self = this;
        $http.post('http://' + propertyCache.config.syncIp + '/dataman/updateconfigdata?factory=' + propertyCache.config.factory + '&line=' + propertyCache.config.line + '&tenant=' + propertyCache.config.tenant + '&pcb=' + pcb + '&efficiency=' + efficiency + '&quality=' + quality+ '&notification=' + notification).then(function (response) {
          deferred.resolve(response);
        }, function (err) {
          $log.debug('ERR', err);
          deferred.reject(err);
        });
        return deferred.promise;
      },

      getBuyerWiseSizeList: function () {
        var deferred = $q.defer();
        $log.debug("sparkDataService : getBuyerWiseSizeList");
        var self = this;
        $http.get('http://' + propertyCache.config.syncIp + '/dataman/getsizelist?factory=' + propertyCache.config.factory + '&tenant=' + propertyCache.config.tenant).then(function (response) {
          console.log("getBuyerWiseSizeList ", response);
          dataPersistenceService.removeBuyerWiseSizeList().then(function(res){
            console.log("Removed rows ------> "+ res.rows.length);
            var data = response['data'];
            for(var i =0;i< data.length;i++){
              var eventToSend = new Object();
              eventToSend.SizeName = JSON.stringify(data[i]);
              dataPersistenceService.insertBuyerWiseSizeList(eventToSend);
            }
          },function(err){
            console.log("No getBuyerWiseSizeList to remove !");
          });
          deferred.resolve(response);
        }, function (err) {
          console.log('ERR', err);
          deferred.reject(err);
        })

        return deferred.promise;
      },

      sendUpdateAcknowledgement: function(){
        var deferred = $q.defer();
        $log.debug("sparkDataService : sendUpdateAcknowledgement");

        $http.get('http://'+propertyCache.config.syncIp+'/deploy/ack?tenant=' + propertyCache.config.tenant + '&factory='+propertyCache.config.factory+'&cluster='+ propertyCache.config.cluster+'&module_id='+propertyCache.config.line +'&license='+propertyCache.config.license+'&mac='+propertyCache.macAddress+'&ipAddress='+propertyCache.ipAddress+'&user='+propertyCache.currentUser+'&version='+configData.version+'&datetime='+new Date().getTime()+"&appType="+configData.appType).then(function (resp) {
          $log.debug('Ack Success !', resp);
          deferred.resolve(resp);
        }, function (err) {
          $log.debug('ERR', err);
          deferred.reject(err);
        })

        return deferred.promise;
      },

      //get data from server
      get: function (query) {
        $log.debug("sparkDataService : get", query);
      },

      getFormattedDate: function () {

        var d = new Date();
        var month = '' + (d.getMonth() + 1);
        var day = '' + d.getDate();
        var year = d.getFullYear();

        if (month.length < 2)
          month = '0' + month;
        if (day.length < 2)
          day = '0' + day;
        currentDate = [year, month, day].join('.');
        return [year, month, day].join('.');
      },
      getFormattedCurrentDate: function () {
        //
        //if (currentDate != "")
        //  return currentDate;

        var d = new Date();
        var month = '' + (d.getMonth() + 1);
        var day = '' + d.getDate();
        var year = d.getFullYear();

        if (month.length < 2)
          month = '0' + month;
        if (day.length < 2)
          day = '0' + day;
        currentDate = [year, month, day].join('.');
        return [year, month, day].join('.');
      },
      getFormattedCurrentDateDash: function () {
        //
        //if (currentDate != "")
        //  return currentDate;

        var d = new Date();
        var month = '' + (d.getMonth() + 1);
        var day = '' + d.getDate();
        var year = d.getFullYear();

        if (month.length < 2)
          month = '0' + month;
        if (day.length < 2)
          day = '0' + day;
        currentDate = [year, month, day].join('-');
        return [year, month, day].join('-');
      }


    };
  }]);
