/**
 * 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) {

        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;

        $http.get('http://' + propertyCache.config.syncIp + '/dataman/plannames?factory=' + propertyCache.config.factory + '&module=' + propertyCache.config.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();
        $http.get('http://' + propertyCache.config.syncIp + '/dataman/synchronize?date=' + self.getFormattedDate() + '&factory=' + propertyCache.config.factory + '&line=' + propertyCache.config.line + '&tenant=' + propertyCache.config.tenant).then(function (response) {

          // have to refactor

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

          var val = response['data'];

          var data = new Object();
          data.date = self.getFormattedDate();
          data.name = 'ftt';
          data.count = val['fttCount'];
          dataPersistenceService.syncCountPreProcess(data);

          var data = new Object();
          data.date = self.getFormattedDate();
          data.name = 'defects';
          data.count = val['defectCount'];
          dataPersistenceService.syncCountPreProcess(data);

          var data = new Object();
          data.name = 'rwtogood';
          data.date = self.getFormattedDate();
          data.count = val['reworkCount'];
          dataPersistenceService.syncCountPreProcess(data);

          var data = new Object();
          data.name = 'reject';
          data.count = val['rejectCount'];
          data.date = self.getFormattedDate();
          dataPersistenceService.syncCountPreProcess(data);

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

        $http.get('http://' + propertyCache.config.syncIp + '/dataman/unrwkdefects?date=' + self.getFormattedDate() + '&factory=' + propertyCache.config.factory + '&line=' + propertyCache.config.line + '&tenant=' + propertyCache.config.tenant).then(function (response) {
          //$log.debug("Sync Session Plans response----> "+ this.response);
          dataPersistenceService.removeAllDefectCategories().then(function (result) {
            var home = response['data'];
            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;

        $http.get('http://' + propertyCache.config.syncIp + '/dataman/getsiluhouttes?factory=' + propertyCache.config.factory +
        '&line=' + propertyCache.config.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;

        $http.get('http://' + propertyCache.config.syncIp + '/dataman/getstylenamesforfivedays?factory=' + propertyCache.config.factory + '&line=' + propertyCache.config.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;
      },


      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(){
        $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()).then(function (resp) {
          $log.debug('Ack Success !', resp);
          deferred.resolve(resp);
        }, function (err) {
          $log.debug('ERR', err);
          deferred.reject(err);
        })
      },

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


    };
  }]);
