/**
 * Created by shadeeka on 11/29/15.
 */
angular.module('app.services')
// =========================================================================
// data persistence  service
// =========================================================================

  .factory('dataPersistenceService', ['$resource', '$cordovaSQLite', '$log', '$q', '$rootScope', 'propertyCache', function ($resource, $cordovaSQLite, $log, $q, $rootScope, propertyCache) {
    var db = null;
    var currentDate = "";
    var _self = this;

    return {

      // create tables
      init: function () {
        $log.debug("database init");

        db = $cordovaSQLite.openDB({name: dbSettings.name, location: "default"});

        // $cordovaSQLite.execute(db, "DROP TABLE DailyCount");

        $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS DailyCount (Date text, Type text , Style text , SO text , LI text, Count integer)");
        $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS BasicConfiguration (Date text, Key text , Value text)");
        $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS DayStart (Date text, Key text , Value text)");
        $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS UserRole (Username text, Password text)");
        $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS NetworkFaliure (Id integer primary key autoincrement not null ,Type text,EndPoint text, Date text , Data text,Status text,MacAddress text)");

        // $cordovaSQLite.execute(db, "DROP TABLE DefectCategories");

        $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS DefectCategories (Id integer primary key autoincrement not null ,Date text, Defect text ,Operation text , Style text , SO text , LI text)");
        $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS SessionPlans (ID integer primary key autoincrement not null ,FactoryId text,LineId text,Name text,StartTime text,EndTime text,Type text,Message text,PlanOrder text)");
        $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS PlanNames (ID integer primary key autoincrement not null ,Name text,Time text)");
        $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS Siluhouttes (ID integer primary key autoincrement not null ,Name text)");
        $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS Styles_Po_Colour (ID integer primary key autoincrement not null ,Style text , Po text , Colour text)");
        $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS Style_Operation (ID integer primary key autoincrement not null ,Style text ,Operation text)");
        $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS IssueList  (ID integer primary key autoincrement not null  ,IssueName text)");
        $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS RejectList (ID integer primary key autoincrement not null  ,RejectName text)");
        $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS sizeList (ID integer primary key autoincrement not null  ,SizeName text)");
        $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS summery (Id integer primary key autoincrement not null,Line text,Station text,Po text,Color text,Style text,Date text, Hour integer ,Epoch text, FttPcs integer, DefectPcs integer,DefectivePcs integer,RectifiedPcs integer,RejectPcs integer,DefectIssue text,DefectOperation text)");
        $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS StartedStyles (Date text, Style text , SO text , LI text)");
        $log.debug("Created the DB and the table !");


        $cordovaSQLite.execute(db, "CREATE INDEX IF NOT EXISTS Date_index , Type_index On DailyCount (Date , Type)");
        $cordovaSQLite.execute(db, "CREATE INDEX IF NOT EXISTS Key_index On BasicConfiguration (Key)");
        $cordovaSQLite.execute(db, "CREATE INDEX IF NOT EXISTS Date_index , Key_index On DayStart (Date , Key)");
        $cordovaSQLite.execute(db, "CREATE INDEX IF NOT EXISTS Id_index ,Type_index On NetworkFaliure (Id , Type)");
        $cordovaSQLite.execute(db, "CREATE INDEX IF NOT EXISTS Id_index , Date_index ,Defect_index On DefectCategories (Date, Id, Defect)");
        $cordovaSQLite.execute(db, "CREATE INDEX IF NOT EXISTS ID_index On SessionPlans (ID)");
        $cordovaSQLite.execute(db, "CREATE INDEX IF NOT EXISTS ID_index On PlanNames (ID)");
        $cordovaSQLite.execute(db, "CREATE INDEX IF NOT EXISTS ID_index On Siluhouttes (ID)");
        $cordovaSQLite.execute(db, "CREATE INDEX IF NOT EXISTS ID_index On Style_Operation (ID)");
        $cordovaSQLite.execute(db, "CREATE INDEX IF NOT EXISTS ID_index On IssueList (ID)");
        $cordovaSQLite.execute(db, "CREATE INDEX IF NOT EXISTS ID_index On RejectList (ID)");
        $cordovaSQLite.execute(db, "CREATE INDEX IF NOT EXISTS ID_index On Styles_Po_Colour (ID)");
        $log.debug("DB Indexed !");

      },
      getHourByEpoch: function (epoch) {
        console.debug("database getHourByEpoch");
        var sessionPlan = propertyCache.day_start.sessionPlanDetail;
        var result = 0;
        if (sessionPlan != undefined && sessionPlan != "") {
          var keys = Object.keys(sessionPlan[0]);
          for (var i = 1; i < keys.length; i++) {
            var startEpoch = sessionPlan[0][i].sE;
            var endEpoch = sessionPlan[0][i].eE;
            result = i;
            if (startEpoch <= epoch && endEpoch >= epoch) {
              propertyCache.setWorkingHour(result);
              return result;
            }
          }
        }
        return propertyCache.workingHour + 1;//in not selected pass last hour
        console.debug("database getHourByEpoch");
      },

      //insert button count events to the local database
      dailyCountPreProcess: function (eventToSend) {
        console.debug("database dailyCountPreProcess");
        var deferred = $q.defer();
        var pr = this.selectDailyCount(eventToSend);
        var _self = this;
        pr.then(function (result) {
          if (result.rows.length > 0) {
            eventToSend.count = result.rows.item(0).Count;
            eventToSend.count += eventToSend.data.value;
            $log.debug("Count-> " + eventToSend.count);
            _self.updateDailyCount(eventToSend);
          }
        }, function (result) {
          _self.insertDailyCount(eventToSend);
        });
        $log.debug("After the selection !");

        var ppr = this.selectDailyCount(eventToSend);
        ppr.then(function (result) {
          deferred.resolve(result);
        }), function (result) {
          deferred.reject();
        };

        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 = this.getHourByEpoch(eventToSend.datetime);
        eventToSendSummery.epoch = eventToSend.datetime;

        if (eventToSend.name == "ftt") {
          eventToSendSummery.fttPcs = eventToSend.data.value;
          eventToSendSummery.defectPcs = 0;
          eventToSendSummery.defectivePcs = 0;
          eventToSendSummery.rectifiedPcs = 0;
          eventToSendSummery.rejectPcs = 0;
          eventToSendSummery.defectIssue = "";
          eventToSendSummery.defectOperation = "";
        } else if (eventToSend.name == "defects") {
          eventToSendSummery.fttPcs = 0;
          eventToSendSummery.defectPcs = eventToSend.data.issues[0].locations.length;
          eventToSendSummery.defectivePcs = eventToSend.data.value;
          eventToSendSummery.rectifiedPcs = 0;
          eventToSendSummery.rejectPcs = 0;
          var issues = eventToSend.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 (eventToSend.name == "rwtogood") {
          eventToSendSummery.fttPcs = 0;
          eventToSendSummery.defectPcs = 0;
          eventToSendSummery.defectivePcs = 0;
          eventToSendSummery.rectifiedPcs = eventToSend.data.value;
          eventToSendSummery.rejectPcs = 0;
          eventToSendSummery.defectIssue = "";
          eventToSendSummery.defectOperation = "";
        } else if (eventToSend.name == "reject") {
          eventToSendSummery.fttPcs = 0;
          eventToSendSummery.defectPcs = 0;
          eventToSendSummery.defectivePcs = 0;
          eventToSendSummery.rectifiedPcs = 0;
          eventToSendSummery.rejectPcs = eventToSend.data.value;
          eventToSendSummery.defectIssue = "";
          eventToSendSummery.defectOperation = "";
        }
        this.insertSummery(eventToSendSummery);
        return deferred.promise;
      },

      // please do not call this method to insert daily count.
      insertDailyCount: function (eventToSend) {
        if (eventToSend.count == undefined) {
          eventToSend.count = 0
        }
        console.debug("database insertDailyCount");
        var query = "INSERT INTO DailyCount (Date, Type , Style , SO , LI , Count) VALUES (?,?,? ,? ,? ,?)";
        $cordovaSQLite.execute(db, query, [this.getFormattedDate(), eventToSend.name, eventToSend.data.style, eventToSend.data.so, eventToSend.data.li, eventToSend.data.value]).then(function (res) {
          $log.debug("INSERT ID -> " + eventToSend.name, eventToSend.data.value);
        }, function (err) {
          $log.debug(err);
        });
      },

      //update the daily count data.
      updateDailyCount: function (eventToSend) {
        console.debug("database updateDailyCount");

        _self.date = this.getFormattedDate();

        this.selectStyleSoLiWiseDailyCount(eventToSend).then(function (res) {

          $log.debug("When update selection --> ", res);

          _self.countToUpdate = res.rows.item(0).Count + eventToSend.data.value;

          var query = "UPDATE DailyCount set Count = '" + _self.countToUpdate + "' where  Type = '" + eventToSend.name + "' and Date = '" + _self.date + "' and Style ='" + eventToSend.data.style + "' and SO = '" + eventToSend.data.so + "' and LI = '" + eventToSend.data.li + "'  ";
          $cordovaSQLite.execute(db, query).then(function (res) {
            $log.debug("Updated ! ", eventToSend.name, eventToSend.value);
          }, function (err) {
            $log.debug(err);
          });

        }, function (error) {

          $log.debug("Error----------------------> ", error)

        });

      },

      //get the daily count data.
      selectDailyCount: function (eventToSend) {
        console.debug("database selectDailyCount");
        var deferred = $q.defer();
        var query = "SELECT Date ,Type ,Count FROM DailyCount WHERE Type = ? and Date = ? ";
        $cordovaSQLite.execute(db, query, [eventToSend.name, this.getFormattedDate()]).then(function (res) {
          response = res;
          if (res.rows.length > 0) {
            deferred.resolve(res);
          } else {
            deferred.reject();
          }
        }, function (err) {
          $log.debug(err);
          deferred.reject();
        });
        return deferred.promise;
      },

      selectStyleSoLiWiseDailyCount: function (eventToSend) {
        console.debug("database selectDailyCount");
        var deferred = $q.defer();
        var query = "SELECT Date ,Type , Style , SO , LI ,Count FROM DailyCount WHERE Type = ? and Date = ? and Style = ? and SO = ? and LI = ? ";
        $cordovaSQLite.execute(db, query, [eventToSend.name, this.getFormattedDate(), eventToSend.data.style, eventToSend.data.so, eventToSend.data.li]).then(function (res) {
          response = res;
          if (res.rows.length > 0) {
            $log.debug("Inserted Counts ! ", res);
            deferred.resolve(res);
          } else {
            deferred.reject();
          }
        }, function (err) {
          $log.debug(err);
          deferred.reject();
        });
        return deferred.promise;
      },

      selectStyleSoLiWiseWithoutTypeDailyCount: function (eventToSend) {
        console.debug("database selectDailyCount");
        var deferred = $q.defer();
        var query = "SELECT Date ,Type , Style , SO , LI ,Count FROM DailyCount WHERE Date = ? and Style = ? and SO = ? and LI = ? ";
        $cordovaSQLite.execute(db, query, [this.getFormattedDate(), eventToSend.data.style, eventToSend.data.so, eventToSend.data.li]).then(function (res) {
          response = res;
          if (res.rows.length > 0) {
            $log.debug("Inserted Counts ! ", res);
            deferred.resolve(res);
          } else {
            deferred.reject();
          }
        }, function (err) {
          $log.debug(err);
          deferred.reject();
        });
        return deferred.promise;
      },

      selectStyleWiseDailyCount: function (eventToSend) {
        console.debug("database selectDailyCount");
        var deferred = $q.defer();
        var query = "SELECT Date ,Type , Style , SO , LI ,Count FROM DailyCount WHERE Type = ? and Date = ? and Style = ? ";
        $cordovaSQLite.execute(db, query, [eventToSend.name, this.getFormattedDate(), eventToSend.data.style]).then(function (res) {
          response = res;
          if (res.rows.length > 0) {
            $log.debug("Inserted Counts ! ", res);
            deferred.resolve(res);
          } else {
            deferred.reject();
          }
        }, function (err) {
          $log.debug(err);
          deferred.reject();
        });
        return deferred.promise;
      },

      selectLiWiseDailyCount: function (eventToSend) {
        console.debug("database selectDailyCount");
        var deferred = $q.defer();
        var query = "SELECT Date ,Type , Style , SO , LI ,Count FROM DailyCount WHERE Type = ? and Date = ? and LI = ? ";
        $cordovaSQLite.execute(db, query, [eventToSend.name, this.getFormattedDate(), eventToSend.data.li]).then(function (res) {
          response = res;
          if (res.rows.length > 0) {
            $log.debug("Inserted Counts ! ", res);
            deferred.resolve(res);
          } else {
            deferred.reject();
          }
        }, function (err) {
          $log.debug(err);
          deferred.reject();
        });
        return deferred.promise;
      },

      selectSoWiseDailyCount: function (eventToSend) {
        console.debug("database selectDailyCount");
        var deferred = $q.defer();
        var query = "SELECT Date ,Type , Style , SO , LI ,Count FROM DailyCount WHERE Type = ? and Date = ? and SO = ? ";
        $cordovaSQLite.execute(db, query, [eventToSend.name, this.getFormattedDate(), eventToSend.data.so]).then(function (res) {
          response = res;
          if (res.rows.length > 0) {
            $log.debug("Inserted Counts ! ", res);
            deferred.resolve(res);
          } else {
            deferred.reject();
          }
        }, function (err) {
          $log.debug(err);
          deferred.reject();
        });
        return deferred.promise;
      },


      //get all the daily count data.
      selectAllTheDailyCount: function () {
        console.debug("database selectAllTheDailyCount");
        var deferred = $q.defer();
        var query = "SELECT Date ,Type ,Count FROM DailyCount where Date = '" + this.getFormattedDate() + "' ";
        $cordovaSQLite.execute(db, query).then(function (res) {
          response = res;
          if (res.rows.length > 0) {
            deferred.resolve(res);
            $log.debug("Daily Count from the DB -------> ", res);
          } else {
            deferred.reject();
          }
        }, function (err) {
          $log.debug(err);
          deferred.reject();
        });
        return deferred.promise;
      },


      //insert daily count data into local database

      insertNetworkFailureData: function (eventToSend) {
        console.debug("database insertNetworkFailureData");
        var query = "INSERT INTO NetworkFaliure (Date, Type ,EndPoint, Data ,Status,MacAddress) VALUES (?,?,?,?,?,?)";
        $cordovaSQLite.execute(db, query, [this.getFormattedDate(), eventToSend.name, eventToSend.endPoint, JSON.stringify(eventToSend.data), eventToSend.status, eventToSend.macAddress]).then(function (res) {
          $log.debug("INSERT ID (Network faliure )-> ", res.insertId, eventToSend.name, eventToSend.endPoint, JSON.stringify(eventToSend.data), eventToSend.status);
        }, function (err) {
          $log.debug(err);
        });
      },


      selectNetworkFaliure: function () {
        console.debug("database selectNetworkFaliure");
        var deferred = $q.defer();
        var query = "SELECT Id, Date ,Type ,EndPoint ,Data,MacAddress FROM NetworkFaliure where Status = 'PENDING'   LIMIT  10 ";
        $cordovaSQLite.execute(db, query).then(function (res) {
          $log.debug("network faliure selection ----> ", res.rows.length);
          if (res.rows.length > 0) {
            deferred.resolve(res);
          } else {
            deferred.reject();
          }
        }, function (err) {
          $log.debug(err);
          deferred.reject();
        });
        return deferred.promise;
      }, countNetworkFaliurePending: function () {
        console.debug("database countNetworkFaliure");
        var deferred = $q.defer();
        var query = "SELECT count(*) as cnt FROM NetworkFaliure where Status = 'PENDING' ";
        $cordovaSQLite.execute(db, query).then(function (res) {
          deferred.resolve(res);
        }, function (err) {
          $log.debug(err);
          deferred.reject();
        });
        return deferred.promise;
      }, countNetworkFaliureSent: function () {
        console.debug("database countNetworkFaliure");
        var deferred = $q.defer();
        var query = "SELECT count(*) as cnt FROM NetworkFaliure where Status = 'SENT' ";
        $cordovaSQLite.execute(db, query).then(function (res) {
          deferred.resolve(res);
        }, function (err) {
          $log.debug(err);
          deferred.reject();
        });
        return deferred.promise;
      }, updateNetworkFaliures: function (eventToSend) {
        console.debug("database updateDailyCount");
        var query = "UPDATE NetworkFaliure set Status = '" + eventToSend.status + "' where  Id = '" + eventToSend.id + "' ";
        $cordovaSQLite.execute(db, query).then(function (res) {
          $log.debug("Updated NetworkFaliure ! ", eventToSend.id, eventToSend.status);
        }, function (err) {
          $log.debug(err);
        });
      }, updateAllNetworkFaliures: function (status) {
        console.debug("database updateAllNetworkFaliures");
        var query = "UPDATE NetworkFaliure set Status = '" + status + "' ";
        $cordovaSQLite.execute(db, query).then(function (res) {
          $log.debug("Updated updateAllNetworkFaliures ! ", status);
        }, function (err) {
          $log.debug(err);
        });
      },

      removeNetworkFaliures: function (eventToSend) {
        console.debug("database removeNetworkFaliures");
        var deferred = $q.defer();
        var query = "Delete from NetworkFaliure where Id = '" + eventToSend.id + "' ";
        $cordovaSQLite.execute(db, query).then(function (res) {
          $log.debug("Removed ! ", eventToSend);
          deferred.resolve(eventToSend);
        }, function (err) {
          $log.debug("Error in removing removeNetworkFaliures ! ");
          deferred.reject();
        });

        return deferred.promise;
      },

      // insert defect category data
      insertDefectCategory: function (eventToSend) {
        console.debug("database insertDefectCategory");
        var deferred = $q.defer();
        var query = "INSERT INTO DefectCategories (Date, Defect , Style , SO , LI) VALUES (?,?,?,?,?)";
        $cordovaSQLite.execute(db, query, [eventToSend.date, eventToSend.defect, eventToSend.style, eventToSend.so, eventToSend.li]).then(function (res) {
          $log.debug("INserted Cats -----------> ", eventToSend.defect);
          deferred.resolve(eventToSend);
        }, function (err) {
          $log.debug("Error insert Defect Category " + err);
          deferred.reject();
        });

        return deferred.promise;
      },

      selectDefectCategories: function () {
        console.debug("database selectDefectCategories");
        var deferred = $q.defer();
        var query = "SELECT Id ,Date ,Defect FROM DefectCategories where Date = '" + this.getFormattedDate() + "' ";
        $cordovaSQLite.execute(db, query).then(function (res) {
          deferred.resolve(res);
        }, function (err) {
          $log.debug(err);
          deferred.reject();
        });
        return deferred.promise;
      },

      selectStyleSoLiWiseDefectCategories: function (style, so, li) {
        console.debug("database selectDefectCategories");
        var deferred = $q.defer();
        var query = "SELECT Id ,Date ,Defect FROM DefectCategories where Date = '" + this.getFormattedDate() + "' and Style = '" + style + "' and SO = '" + so + "' and LI = '" + li + "' ";
        $cordovaSQLite.execute(db, query).then(function (res) {
          deferred.resolve(res);
        }, function (err) {
          $log.debug(err);
          deferred.reject();
        });
        return deferred.promise;
      },

      //remove defect categories.
      removeDefectCategories: function (eventToSend) {
        console.debug("database removeDefectCategories");
        var query = "Delete from DefectCategories where Defect = '" + eventToSend.name + "'  and Id = '" + eventToSend.id + "' ";
        $cordovaSQLite.execute(db, query).then(function (res) {
          $log.debug("Removed Defect Categories ! ", eventToSend.name, eventToSend.id);
        }, function (err) {
          $log.debug(err);
        });
      },

      removeStyleSoLiWiseDefectCategories: function (eventToSend) {
        console.debug("database removeDefectCategories");
        var query = "Delete from DefectCategories where Defect = '" + eventToSend.name + "'  and Id = '" + eventToSend.id + "' and Style = '" + eventToSend.style + "' and SO = '" + eventToSend.so + "' and LI = '" + eventToSend.li + "' ";
        $cordovaSQLite.execute(db, query).then(function (res) {
          $log.debug("Removed Defect Categories ! ", eventToSend.name, eventToSend.id);
        }, function (err) {
          $log.debug(err);
        });
      },

      //remove all defect categories.
      removeAllDefectCategories: function (eventToSend) {
        console.debug("database removeAllDefectCategories");
        var deferred = $q.defer();
        var query = "Delete from DefectCategories";
        $cordovaSQLite.execute(db, query).then(function (res) {
          $log.debug("Removed Defect Categories ! ");
          deferred.resolve(res);
        }, function (err) {
          deferred.reject();
          $log.debug(err);
        });
        return deferred.promise;
      },


      //remove all defect categories.
      removeAllAuthentication: function (eventToSend) {
        console.debug("database removeAllAuthentication");
        var deferred = $q.defer();
        var query = "Delete from UserRole";
        $cordovaSQLite.execute(db, query).then(function (res) {
          $log.debug("Removed UserRole ! ");
          deferred.resolve(res);
        }, function (err) {
          deferred.reject();
          $log.debug(err);
        });
        return deferred.promise;
      },
      //remove defect categories.
      removeUndoDefectCategories: function (eventToSend) {
        console.debug("database removeUndoDefectCategories");
        var query = "Delete from DefectCategories where Defect = '" + eventToSend.name + "' and Id = (SELECT MAX(Id) FROM DefectCategories);";
        $cordovaSQLite.execute(db, query).then(function (res) {
          $log.debug("Removed ! ", eventToSend.name);
        }, function (err) {
          $log.debug(err);
        });
      },


      // insert Configuration data
      insertConfiguration: function (eventToSend) {
        console.debug("database insertConfiguration");
        var _self = this;
        var pr = this.removeBasicConfiguration(eventToSend);
        pr.then(function (result) {
          var query = "INSERT INTO BasicConfiguration (Date , Key , Value) VALUES (?,?,?)";
          $cordovaSQLite.execute(db, query, [_self.getFormattedDate(), eventToSend.key, eventToSend.value]).then(function (res) {
            $log.debug("INSERT Configurations -> " + res.insertId);
            $log.debug("INSERT Configurations -> " + eventToSend.key);
          }, function (err) {
            $log.debug("Error inserting configurations " + err);
          });
        })
      },

      //remove configurations.
      removeBasicConfiguration: function (eventToSend) {
        console.debug("database removeBasicConfiguration");
        var deferred = $q.defer();
        var query = "Delete from BasicConfiguration where Key = '" + eventToSend.key + "' ";
        $cordovaSQLite.execute(db, query).then(function (res) {
          $log.debug("Removed configuration ! " + eventToSend.key);
          deferred.resolve(res);
        }, function (err) {
          $log.debug(err);
          deferred.reject();
        });
        return deferred.promise;
      },

      selectConfigurations: function () {
        console.debug("database selectConfigurations");
        var deferred = $q.defer();
        var query = "SELECT Date , Key , Value FROM BasicConfiguration";
        $cordovaSQLite.execute(db, query).then(function (res) {
          response = res;
          if (res.rows.length > 0) {
            deferred.resolve(res);
          } else {
            deferred.reject();
          }
        }, function (err) {
          $log.debug(err);
          deferred.reject(err);
        });
        return deferred.promise;
      },


      selectGivenConfiguration: function (key) {
        console.debug("database selectGivenConfiguration");
        var deferred = $q.defer();
        var query = "SELECT Key , Value FROM BasicConfiguration where Key ='" + key + "' ";
        $cordovaSQLite.execute(db, query).then(function (res) {
          response = res;
          if (res.rows.length > 0) {
            deferred.resolve(res);
          } else {
            deferred.reject();
          }
        }, function (err) {
          $log.debug(err);
          deferred.reject(err);
        });
        return deferred.promise;
      },


      saveAuthentication: function (data) {
        console.debug("database saveAuthentication");
        var query = "INSERT INTO UserRole (Username , Password) VALUES (?,?)";
        $cordovaSQLite.execute(db, query, [data.username, data.password]).then(function (res) {
          $log.debug("INSERT ID -> " + res.insertId);
        }, function (err) {
          $log.debug(err);
        });
      },

      getAuthentication: function (data) {
        console.debug("database getAuthentication");
        var deferred = $q.defer();
        var query = "SELECT Password FROM UserRole WHERE Username='" + data + "'";
        $cordovaSQLite.execute(db, query, data).then(function (res) {
          $log.debug("user pass -> " + res);
          deferred.resolve(res);
        }, function (err) {
          $log.debug(err);
          deferred.reject(err);
        });
        return deferred.promise;
      },

      saveSessionPlanNames: function (data) {
        console.debug("database saveSessionPlanNames");
        var _self = this;
        var deferred = $q.defer();
        var removepr = this.removeSessionPlans().then(function (response) {
          var query = "INSERT INTO PlanNames (Name , Time) VALUES (?,?)";
          $cordovaSQLite.execute(db, query, [data.name, data.time]).then(function (res) {
            deferred.resolve(response);
            $log.debug("INSERT ID -> " + res.insertId);
            $log.debug("INSERT ID -> ", data.name);
          }, function (err) {
            deferred.reject(err);
            $log.debug(err);
          });
        })
        return deferred.promise;
      },


      //remove defect categories.
      removeSessionPlans: function () {
        console.debug("database removeSessionPlans");
        var deferred = $q.defer();
        var query = "Delete from PlanNames";
        $cordovaSQLite.execute(db, query).then(function (res) {
          $log.debug("Removed Plans ! ");
          deferred.resolve(res);
        }, function (err) {
          $log.debug(err);
          deferred.reject();
        });
        return deferred.promise;
      },

      selectSessionPlanNames: function () {
        console.debug("database selectSessionPlanNames");
        var deferred = $q.defer();
        var query = "SELECT Name FROM PlanNames";
        $cordovaSQLite.execute(db, query).then(function (res) {
          if (res.rows.length > 0) {
            for (var i = 0; i < res.rows.length; i++) {
              $log.debug("Session plan name s--> ", res.rows.item(i).Name);
            }
            deferred.resolve(res);
          } else {
            deferred.reject();
          }
        }, function (err) {
          $log.debug(err);
          deferred.reject(err);
        });
        return deferred.promise;
      },

      syncCountPreProcess: function (data) {
        console.debug("database syncCountPreProcess");
        if (data.count == undefined) {
          data.count = 0
        }
        var _self = this;
        this.selectDailyCount(data).then(function (response) {
          if (response.rows.length > 0) {
            _self.updateDailyCount(data);
            $rootScope.$broadcast("update-btn-counts");
          }
        }, function (result) {
          _self.insertDailyCount(data);
          $rootScope.$broadcast("update-btn-counts");
        })
      },

      syncStyleSoLiWiseCountPreProcess: function (data) {
        console.debug("database syncStyleSoLiWiseCountPreProcess");
        if (data.count == undefined) {
          data.count = 0
        }
        var _self = this;
        _self.cleanDailyCountTable(data.data.style , data.data.so , data.data.li).then(function (result){
          _self.insertDailyCount(data);
          $rootScope.$broadcast("update-btn-counts");
        }, function (error){
          _self.insertDailyCount(data);
          $rootScope.$broadcast("update-btn-counts");
        });
      },

      cleanDailyCountTable : function (style , so , li){
        console.debug("database cleanDailyCountTable");
        var deferred = $q.defer();
        var query = "Delete from DailyCount where Style = '" + style + "' and Date ='"+this.getFormattedDate()+"' and SO ='"+so+"' and LI ='"+li+"' ";
        $cordovaSQLite.execute(db, query).then(function (res) {
          deferred.resolve(res);
        }, function (err) {
          $log.debug("Error in removing cleanDailyCountTable ! ");
          deferred.reject(err);
        });
        return deferred.promise;
      },

      disableApp: function () {
        console.debug("database disableApp");
        var query = "INSERT INTO BasicConfiguration (Date, Key , Value) VALUES (?,?)";
        var deferred = $cordovaSQLite.execute(db, query, [this.getFormattedDate(), "AppDisable", "Enabled"]);
        return deferred;
      },

      enableApp: function () {
        console.debug("database enableApp");
        var query = "Delete from BasicConfiguration where Key = '" + "AppDisable" + "' ;";
        $cordovaSQLite.execute(db, query).then(function (res) {
          $log.debug("Removed ! ");
        }, function (err) {
          $log.debug(err);
        });
      },

      selectApplicationStatus: function () {
        console.debug("database selectApplicationStatus");
        var deferred = $q.defer();
        var query = "SELECT Value FROM BasicConfiguration where Key = AppDisable ";
        $cordovaSQLite.execute(db, query).then(function (res) {
          response = res;
          if (res.rows.length > 0) {
            deferred.resolve(res);
          } else {
            deferred.reject();
          }
        }, function (err) {
          $log.debug(err);
          deferred.reject(err);
        });
        return deferred.promise;
      },

      getFormattedDate: function () {
        console.debug("database getFormattedDate");
        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('.');
      },

      //////////////////////day start ////////////////////////

      insertDayStart: function (eventToSend) {
        console.debug("database insertDayStart");
        var _self = this;
        var pr = this.removeDayStart(eventToSend);
        pr.then(function (result) {
          var query = "INSERT INTO DayStart (Date , Key , Value) VALUES (?,?,?)";
          $cordovaSQLite.execute(db, query, [_self.getFormattedDate(), eventToSend.key, eventToSend.value]).then(function (res) {
            $log.debug("INSERT DayStart -> " + res.insertId);
            $log.debug("INSERT DayStart -> " + eventToSend.key);
          }, function (err) {
            $log.debug("Error inserting DayStart " + err);
          });
        })
      },


      removeDayStart: function (eventToSend) {
        console.debug("database removeDayStart");
        var _self = this;
        var deferred = $q.defer();
        var query = "Delete from DayStart where Key = '" + eventToSend.key + "' and Date = '" + _self.getFormattedDate() + "'  ";
        $cordovaSQLite.execute(db, query).then(function (res) {
          $log.debug("Removed DayStart ! " + eventToSend.key);
          deferred.resolve(res);
        }, function (err) {
          $log.debug(err);
          deferred.reject();
        });
        return deferred.promise;
      },

      selectDayStart: function () {
        console.debug("database selectDayStart");
        var _self = this;
        var deferred = $q.defer();
        var query = "SELECT Date , Key , Value FROM DayStart where Date = '" + _self.getFormattedDate() + "' ";
        $log.debug("Date day start ----------> ", _self.getFormattedDate());
        $cordovaSQLite.execute(db, query).then(function (result) {
          if (result.rows.length > 0) {
            deferred.resolve(result);
            $log.debug("Day start selection result--> ", result.rows);
          } else {
            deferred.reject();
          }
        }, function (err) {
          $log.debug("Day start selection error", err);
          deferred.reject(err);
        });
        return deferred.promise;
      },

      insertStartedStyles: function (style , so , li) {
        console.debug("database insertStartedStyles");
        var deferred = $q.defer();
        var _self = this;
        this.selectStyleSoLiWiseStartedStyles(style , so , li).then (function (result) {
            if(result.rows.length <= 0){
              var query = "INSERT INTO StartedStyles (Date , Style , SO , LI) VALUES (?,?,?,?)";
              $cordovaSQLite.execute(db, query, [_self.getFormattedDate(), style , so , li]).then(function (res) {
                $log.debug("INSERT DayStart -> " + res.insertId);
                $log.debug("INSERT DayStart -> " ,style , so , li);
                deferred.resolve(result);
              }, function (err) {
                $log.debug("Error inserting DayStart " + err);
                deferred.reject(err);
              });
            }
        }, function (error){
          var query = "INSERT INTO StartedStyles (Date , Style , SO , LI) VALUES (?,?,?,?)";
          $cordovaSQLite.execute(db, query, [_self.getFormattedDate(), style , so , li]).then(function (result) {
            $log.debug("INSERT DayStart -> " + result.insertId);
            $log.debug("INSERT DayStart -> " ,style , so , li);
            deferred.resolve(result);
          }, function (err) {
            $log.debug("Error inserting DayStart " + err);
            deferred.reject(err);
          });
        });
        return deferred.promise;
      },

      selectStartedStyles: function () {
        console.debug("database selectDayStart");
        var _self = this;
        var deferred = $q.defer();
        var query = "SELECT Date , Style , SO , LI FROM StartedStyles where Date = '" + _self.getFormattedDate() + "' ";
        $log.debug("Date day start ----------> ", _self.getFormattedDate());
        $cordovaSQLite.execute(db, query).then(function (result) {
          if (result.rows.length > 0) {
            deferred.resolve(result);
            $log.debug("Day start selection result--> ", result.rows);
          } else {
            deferred.reject();
          }
        }, function (err) {
          $log.debug("Day start selection error", err);
          deferred.reject(err);
        });
        return deferred.promise;
      },

      selectStyleSoLiWiseStartedStyles: function (style , so , li) {
        console.debug("database selectDayStart");
        var _self = this;
        var deferred = $q.defer();
        var query = "SELECT Date , Style , SO , LI FROM StartedStyles where Date = '" + _self.getFormattedDate() + "' and Style ='"+style+"' and SO ='"+so+"' and LI ='"+li+"' ";
        $log.debug("Date day start ----------> ", _self.getFormattedDate());
        $cordovaSQLite.execute(db, query).then(function (result) {
          if (result.rows.length > 0) {
            deferred.resolve(result);
            $log.debug("Day start selection result--> ", result.rows);
          } else {
            deferred.reject();
          }
        }, function (err) {
          $log.debug("Day start selection error", err);
          deferred.reject(err);
        });
        return deferred.promise;
      },

      selectStartedSos: function (style) {
        console.debug("database selectDayStart");
        var _self = this;
        var deferred = $q.defer();
        var query = "SELECT Date , Style , SO , LI FROM StartedStyles where Date = '" + _self.getFormattedDate() + "' and Style ='"+style+"' ";
        $log.debug("Date day start ----------> ", _self.getFormattedDate());
        $cordovaSQLite.execute(db, query).then(function (result) {
          if (result.rows.length > 0) {
            deferred.resolve(result);
            $log.debug("Day start selection result--> ", result.rows);
          } else {
            deferred.reject();
          }
        }, function (err) {
          $log.debug("Day start selection error", err);
          deferred.reject(err);
        });
        return deferred.promise;
      },

      selectStartedLis: function (style , so) {
        console.debug("database selectDayStart");
        var _self = this;
        var deferred = $q.defer();
        var query = "SELECT Date , Style , SO , LI FROM StartedStyles where Date = '" + _self.getFormattedDate() + "' and SO ='"+so+"' and Style ='"+style+"' ";
        $log.debug("Date day start ----------> ", _self.getFormattedDate());
        $cordovaSQLite.execute(db, query).then(function (result) {
          if (result.rows.length > 0) {
            deferred.resolve(result);
            $log.debug("Day start selection result--> ", result.rows);
          } else {
            deferred.reject();
          }
        }, function (err) {
          $log.debug("Day start selection error", err);
          deferred.reject(err);
        });
        return deferred.promise;
      },


      cleanDb: function () {
        console.debug("database cleanDb");
        var query = "Delete from DailyCount";
        $cordovaSQLite.execute(db, query).then(function (res) {
          $log.debug("Removed DailyCount ! ");
        }, function (err) {
          $log.debug(err);
        });

        var query = "Delete from NetworkFaliure";
        $cordovaSQLite.execute(db, query).then(function (res) {
          $log.debug("Removed NetworkFaliure ! ");
        }, function (err) {
          $log.debug(err);
        });


        var query = "Delete from DefectCategories";
        $cordovaSQLite.execute(db, query).then(function (res) {
          $log.debug("Removed DefectCategories ! ");
        }, function (err) {
          $log.debug(err);
        });

        var query = "Delete from PlanNames";
        $cordovaSQLite.execute(db, query).then(function (res) {
          $log.debug("Removed PlanNames ! ");
        }, function (err) {
          $log.debug(err);
        });

        var query = "Delete from BasicConfigurations";
        $cordovaSQLite.execute(db, query).then(function (res) {
          $log.debug("Removed BasicConfigurations ! ");
        }, function (err) {
          $log.debug(err);
        });
      },

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

      insertSiluhoutte: function (siluhoutte) {
        console.debug("database insertSiluhoutte");
        var deferred = $q.defer();
        var query = "INSERT INTO Siluhouttes (Name) VALUES (?)";
        $cordovaSQLite.execute(db, query, [siluhoutte]).then(function (res) {
          $log.debug("INSERT ID -> " + siluhoutte);
          deferred.resolve(res);
        }, function (err) {
          $log.debug(err);
          deferred.reject(err);
        });
        return deferred.promise;
      },

      selectSiluhouttes: function () {
        console.debug("database selectSiluhouttes");
        var _self = this;
        var deferred = $q.defer();
        var query = "SELECT Name FROM Siluhouttes";
        $cordovaSQLite.execute(db, query).then(function (result) {
          if (result.rows.length > 0) {
            deferred.resolve(result);
          } else {
            deferred.reject();
          }
        }, function (err) {
          deferred.reject(err);
        });
        return deferred.promise;
      },

      removeSiluhoutte: function () {
        console.debug("database removeSiluhoutte");
        var _self = this;
        var deferred = $q.defer();
        var query = "Delete from Siluhouttes";
        $cordovaSQLite.execute(db, query).then(function (res) {
          $log.debug("Removed Siluhouttes ! ");
          deferred.resolve(res);
        }, function (err) {
          deferred.reject(err);
          $log.debug(err);
        });
        return deferred.promise;
      },


      //////////////////////////////// Style_OPerations /////////////////////////////

      insertStyleOperation: function (eventToSend) {
        console.debug("database insertStyleOperation");
        //var deferred = $q.defer();
        var query = "INSERT INTO Style_Operation (Style , Operation) VALUES (?,?)";
        $cordovaSQLite.execute(db, query, [eventToSend.style, eventToSend.operation]).then(function (res) {
          //deferred.resolve(res);
        }, function (err) {
          $log.debug(err);
          //deferred.reject(err);
        });
        //return deferred.promise;
      },

      selectStyleOperations: function (style) {
        console.debug("database selectStyleOperations");
        var _self = this;
        var deferred = $q.defer();
        var query = "SELECT Operation FROM Style_Operation where Style = '" + style + "' ";
        $cordovaSQLite.execute(db, query).then(function (result) {
          if (result.rows.length > 0) {
            deferred.resolve(result);
          } else {
            deferred.reject();
          }
        }, function (err) {
          deferred.reject(err);
        });
        return deferred.promise;
      },

      removeStyleOperation: function () {
        console.debug("database removeStyleOperation");
        var _self = this;
        var deferred = $q.defer();
        var query = "Delete from Style_Operation";
        $cordovaSQLite.execute(db, query).then(function (res) {
          deferred.resolve(res);
        }, function (err) {
          deferred.reject(err);
          $log.debug(err);
        });
        return deferred.promise;
      }, removeDayStartByDate: function (eventToSend) {
        console.debug("database removeDayStartByDate");
        var _self = this;
        var deferred = $q.defer();
        var query = "Delete from DayStart where Date = '" + _self.getFormattedDate() + "'  ";
        $log.debug("query! " + query);
        $cordovaSQLite.execute(db, query).then(function (res) {
          $log.debug("removeDayStart ByDate ! " + eventToSend.date);
          deferred.resolve(res);
        }, function (err) {
          $log.debug("error removeDayStart ByDate ! " + eventToSend.date);
          console.error(err);
          deferred.reject();
        });
        return deferred.promise;
      },
      insertIssue: function (eventToSend) {
        console.debug("database insertIssue");
        //    var deferred = $q.defer();
        var query = "INSERT INTO IssueList (IssueName) VALUES (?)";
        $cordovaSQLite.execute(db, query, [eventToSend.issueName]);
        //.then(function (res) {
        //  $log.debug("INSERTED insertIssue -> " , eventToSend);
        //  //deferred.resolve(res);
        //}, function (err) {
        //  console.error(err);
        //  //deferred.reject(err);
        //});
        //return deferred.promise;
      },

      selectIssues: function () {
        console.debug("database selectIssues");
        var _self = this;
        var deferred = $q.defer();
        var query = "SELECT IssueName FROM IssueList ";
        $cordovaSQLite.execute(db, query).then(function (result) {
          $log.debug("selectIssues from DB -------> ", result);
          if (result.rows.length > 0) {
            deferred.resolve(result);
          } else {
            deferred.reject();
          }
        }, function (err) {
          deferred.reject(err);
        });
        return deferred.promise;
      },

      removeIssueList: function () {
        console.debug("database removeIssueList");
        var _self = this;
        var deferred = $q.defer();
        var query = "Delete from IssueList";
        $cordovaSQLite.execute(db, query).then(function (res) {
          $log.debug("Removed removeIssueList ! ");
          deferred.resolve(res);
        }, function (err) {
          deferred.reject(err);
          console.error(err);
        });
        return deferred.promise;
      },
      insertReject: function (eventToSend) {
        //var deferred = $q.defer();
        var query = "INSERT INTO RejectList (RejectName) VALUES (?)";
        $cordovaSQLite.execute(db, query, [eventToSend.rejectName]);
        //.then(function (res) {
        //  //$log.debug("INSERTED insertReject -> " , eventToSend);
        // // deferred.resolve(res);
        //}, function (err) {
        //  console.error(err);
        //  //deferred.reject(err);
        //});
        // return deferred.promise;
      },

      selectRejects: function () {
        var _self = this;
        var deferred = $q.defer();
        var query = "SELECT RejectName FROM RejectList ";
        $cordovaSQLite.execute(db, query).then(function (result) {
          $log.debug("selectRejects from DB -------> ", result);
          if (result.rows.length > 0) {
            deferred.resolve(result);
          } else {
            deferred.reject();
          }
        }, function (err) {
          deferred.reject(err);
        });
        return deferred.promise;
      },

      removeRejectList: function () {
        var _self = this;
        var deferred = $q.defer();
        var query = "Delete from RejectList";
        $cordovaSQLite.execute(db, query).then(function (res) {
          $log.debug("Removed removeRejects ! ");
          deferred.resolve(res);
        }, function (err) {
          deferred.reject(err);
          console.error(err);
        });
        return deferred.promise;
      },

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

      removeStyles_Po_Colour: function () {
        console.debug("database removeStyles_Po_Colour");
        var _self = this;
        var deferred = $q.defer();
        var query = "Delete from Styles_Po_Colour";
        $log.debug("query! " + query);
        $cordovaSQLite.execute(db, query).then(function (res) {
          $log.debug("removed Styles_Po_Colour ! ", res);
          deferred.resolve(res);
        }, function (err) {
          $log.debug("error removed Styles_Po_Colour !");
          console.error(err);
          deferred.reject();
        });
        return deferred.promise;
      },

      addStyles_Po_Colour: function (event) {
        console.debug("database add Styles_Po_Colour");
        var _self = this;
        var deferred = $q.defer();
        var query = "INSERT INTO Styles_Po_Colour (Style,PO,Colour) VALUES (?,?,?)";
        $cordovaSQLite.execute(db, query, [event.style, event.po, event.colour]).then(function (res) {
          deferred.resolve(res);
          $log.debug("INSERT STYLE -> ", res);
          $log.debug("INSERT PO -> ", res);
          $log.debug("INSERT COLOUR -> ", res);
        }, function (err) {
          $log.debug(err);
          deferred.reject(err);
        });
        return deferred.promise;
      },

      selectAllFromStyles_po_colours: function () {
        console.debug("database selectAllFromStyles_po_colours");
        var _self = this;
        var deferred = $q.defer();
        var query = "SELECT Style,Po,Colour FROM Styles_Po_Colour";
        $cordovaSQLite.execute(db, query).then(function (result) {
          if (result.rows.length > 0) {
            deferred.resolve(result);
          } else {
            deferred.reject();
          }
        }, function (err) {
          deferred.reject(err);
        });
        return deferred.promise;
      },

      selectStyles: function () {
        console.debug("database Styles");
        var _self = this;
        var deferred = $q.defer();
        var query = "SELECT Style FROM Styles_Po_Colour";
        $cordovaSQLite.execute(db, query).then(function (result) {
          if (result.rows.length > 0) {
            deferred.resolve(result);
          } else {
            deferred.reject();
          }
        }, function (err) {
          deferred.reject(err);
        });
        return deferred.promise;
      },


      selectPos: function () {
        console.debug("database selectPos");
        var _self = this;
        var deferred = $q.defer();
        var query = "SELECT Po FROM Styles_Po_Colour";
        $cordovaSQLite.execute(db, query).then(function (result) {
          if (result.rows.length > 0) {
            deferred.resolve(result);
          } else {
            deferred.reject();
          }
        }, function (err) {
          deferred.reject(err);
        });
        return deferred.promise;
      },


      selectColoursPos: function (style) {
        console.debug("database selectColours");
        var _self = this;
        var deferred = $q.defer();
        var query = "SELECT Colour , Po FROM Styles_Po_Colour where Style ='" + style + "'";
        $cordovaSQLite.execute(db, query).then(function (result) {
          if (result.rows.length > 0) {
            deferred.resolve(result);
          } else {
            deferred.reject();
          }
        }, function (err) {
          deferred.reject(err);
        });
        return deferred.promise;
      },

      selectColoursStyles: function (Po) {
        console.debug("database selectColours");
        var _self = this;
        var deferred = $q.defer();
        var query = "SELECT Style , Colour FROM Styles_Po_Colour where Po ='" + Po + "'";
        $cordovaSQLite.execute(db, query).then(function (result) {
          if (result.rows.length > 0) {
            deferred.resolve(result);
          } else {
            deferred.reject();
          }
        }, function (err) {
          deferred.reject(err);
        });
        return deferred.promise;
      },

      selectStylesPos: function (Colour) {
        console.debug("database selectColours");
        var _self = this;
        var deferred = $q.defer();
        var query = "SELECT Po , Style FROM Styles_Po_Colour where Colour ='" + Colour + "'";
        $cordovaSQLite.execute(db, query).then(function (result) {
          if (result.rows.length > 0) {
            deferred.resolve(result);
          } else {
            deferred.reject();
          }
        }, function (err) {
          deferred.reject(err);
        });
        return deferred.promise;
      },

      insertBuyerWiseSizeList: function (eventToSend) {
        //var deferred = $q.defer();
        var query = "INSERT INTO sizeList (SizeName) VALUES (?)";
        $cordovaSQLite.execute(db, query, [eventToSend.SizeName]).then(function (res) {
          $log.debug("INSERTED insertBuyerWiseSizeList -> ", eventToSend);
          // deferred.resolve(res);
        }, function (err) {
          console.error(err);
          //deferred.reject(err);
        });
        // return deferred.promise;
      },

      selectBuyerWiseSizeList: function () {
        var _self = this;
        var deferred = $q.defer();
        var query = "SELECT SizeName FROM sizeList ";
        $cordovaSQLite.execute(db, query).then(function (result) {
          $log.debug("selectBuyerWiseSizeList from DB -------> ", result);
          if (result.rows.length > 0) {
            deferred.resolve(result);
          } else {
            deferred.reject();
          }
        }, function (err) {
          deferred.reject(err);
        });
        return deferred.promise;
      },

      removeBuyerWiseSizeList: function () {
        var _self = this;
        var deferred = $q.defer();
        var query = "Delete from sizeList";
        $cordovaSQLite.execute(db, query).then(function (res) {
          console.log("Removed removeBuyerWiseSizeList ! ");
          deferred.resolve(res);
        }, function (err) {
          deferred.reject(err);
          console.error(err);
        });
        return deferred.promise;
      },

      insertSummery: function (eventToSend) {
        console.debug("database.js   calling insertSummery start", eventToSend);
        var deferred = $q.defer();
        var query = "INSERT INTO summery (Date,Line,Style,Po,Color,Station,Hour,Epoch,FttPcs,DefectPcs,DefectivePcs,RectifiedPcs,RejectPcs,DefectIssue,DefectOperation) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        $cordovaSQLite.execute(db, query, [this.getFormattedDate(), eventToSend.line_id, eventToSend.style,
          eventToSend.po, eventToSend.color, eventToSend.station, eventToSend.hour, eventToSend.epoch, eventToSend.fttPcs,
          eventToSend.defectPcs, eventToSend.defectivePcs, eventToSend.rectifiedPcs, eventToSend.rejectPcs, eventToSend.defectIssue, eventToSend.defectOperation]).then(function (res) {
          deferred.resolve(res);
          console.debug("database.js    insertSummery resolved");
        }, function (err) {
          deferred.reject();
          console.error(err);
          console.debug("database.js    insertSummery error");
        });
        return deferred.promise;
      },
      selectAllSummery: function (line) {
        console.debug("database.js   calling selectAllSummery start");
        var deferred = $q.defer();
        var query = "SELECT Line,Style,Po,Color,Station,Hour,Epoch,FttPcs,DefectPcs,DefectivePcs,RectifiedPcs,RejectPcs,DefectIssue,DefectOperation FROM summery where Date = '" + this.getFormattedDate() + "'";
        $cordovaSQLite.execute(db, query).then(function (res) {
          response = res;
          if (res.rows.length > 0) {
            deferred.resolve(res);
          } else {
            deferred.reject();
          }
          console.debug("database.js    selectAllSummery resolved");
        }, function (err) {
          console.error(err);
          console.debug("database.js    selectAllSummery error");
          deferred.reject();
        });
        return deferred.promise;
      },
      selectSummeryReport: function (line) {
        console.debug("database.js   calling selectSummeryReport start");
        var deferred = $q.defer();
        var query = "SELECT Hour,Style,Po,Color,sum(FttPcs) as totFtt,sum(DefectPcs)  as totDefect,sum(DefectivePcs) as totDefective,sum(RejectPcs) as totReject," +
          " sum(RectifiedPcs) as totRectified " +
          " FROM summery where Date = '" + this.getFormattedDate() + "' group by Hour,Style,Po,Color order by 1";
        $cordovaSQLite.execute(db, query).then(function (res) {
          response = res;
          if (res.rows.length > 0) {
            deferred.resolve(res);
          } else {
            deferred.reject();
          }
          console.debug("database.js    selectSummeryReport resolved");
        }, function (err) {
          console.error(err);
          console.debug("database.js    selectSummeryReport error");
          deferred.reject();
        });
        return deferred.promise;
      },
      removeAllSummery: function () {
        var _self = this;
        var deferred = $q.defer();
        var query = "Delete from summery";
        $cordovaSQLite.execute(db, query).then(function (res) {
          console.log("Removed removeAllSummery ! ");
          deferred.resolve(res);
        }, function (err) {
          deferred.reject(err);
          console.error(err);
        });
        return deferred.promise;
      }

    }
  }])
