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

  .factory('dataPersistenceService', ['$resource', '$cordovaSQLite', '$log', '$q', '$rootScope', function ($resource, $cordovaSQLite, $log, $q, $rootScope) {
    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, "CREATE TABLE IF NOT EXISTS DailyCount (Date text, Type 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)");
        $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS DefectCategories (Id integer primary key autoincrement not null ,Date text, Defect text ,Operation 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)");
        $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 !");

      },

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

        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 , Count) VALUES (?,?,?)";
        $cordovaSQLite.execute(db, query, [this.getFormattedDate(), eventToSend.name, eventToSend.count]).then(function (res) {
          $log.debug("INSERT ID -> " + eventToSend.name, eventToSend.count);
        }, function (err) {
          $log.debug(err);
        });
      },

      //update the daily count data.
      updateDailyCount: function (eventToSend) {
        console.debug("database updateDailyCount");
        var query = "UPDATE DailyCount set Count = '" + eventToSend.count + "' where  Type = '" + eventToSend.name + "' and Date = '" + this.getFormattedDate() + "'  ";
        $cordovaSQLite.execute(db, query).then(function (res) {
          $log.debug("Updated ! ", eventToSend.name, eventToSend.count);
        }, function (err) {
          $log.debug(err);
        });
      },

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


      //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) VALUES (?,?,?,?,?)";
        $cordovaSQLite.execute(db, query, [this.getFormattedDate(), eventToSend.name, eventToSend.endPoint, JSON.stringify(eventToSend.data), eventToSend.status]).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 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) VALUES (?,?)";
        $cordovaSQLite.execute(db, query, [eventToSend.date, eventToSend.defect]).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;
      },

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

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

      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;
      },

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

    }
  }])
