/*
	Copyright James Matteson 2011. All rights reserved.
*/
function gearsDB(){
   var oThis = this;
   var db;
      
   // private
   function hasValue(tableName, valueName, value){
      var has = false;
      var rs = db.execute('select count(*) from ' + tableName + ' where ' + valueName + ' = (?)', [value]);

      if (rs.isValidRow()) {
        has = (parseInt(rs.field(0)) > 0)
      }
      
      rs.close();      
      return has;
   }
   function getStoryIDs(tableName){
      var rs = db.execute('select StoryID from ' + tableName);
      var stories = [];
      var i = 0;
      var storyIDs = '';
      
      while (rs.isValidRow()) {
         if (i >= dataLayer.getMaxStoryIDs()){
            i = 0;
            stories.push(storyIDs);
            storyIDs = '';
         }
         
         if (storyIDs.length > 0){
            storyIDs += ',';
         }
         
         storyIDs += rs.field(0);
         i++;         
         rs.next();
      }
      
      if (storyIDs.length > 0){
         stories.push(storyIDs);
      }
      
      rs.close();
      
      return stories;
   }
   function getStoryIDsByOffset(tableName, lastRowID){
      var sql = 'select StoryID, ROWID from ' + tableName;
      if (lastRowID != null && lastRowID >= 0){
         sql += ' where ROWID < ' + lastRowID;
      }
      sql += ' order by ROWID desc limit ' + dataLayer.getMaxStoryIDs();
      var rs = db.execute(sql);
      var storyIDs = '';
      
      lastRowID = -1;
      
      while (rs.isValidRow()) {
         if (storyIDs.length > 0){
            storyIDs += ',';
         }
         
         storyIDs += rs.field(0);
         lastRowID = rs.field(1);
         rs.next();
      }
      
      rs.close();
            
      return { 'storyIDs': storyIDs, 'lastRowID': lastRowID };
   }
   function isStoryInQueue(storyID){
      return hasValue('StoryQueue', 'StoryID', storyID);
   }
   function isStoryRead(storyID){
      return hasValue('Read', 'StoryID', storyID);
   }
   function isStoryDismissed(storyID){
      return hasValue('Dismissed', 'StoryID', storyID);
   }
   
   /* overridden */

   // db functions
   this.init = function(){
      try{
         db = google.gears.factory.create('beta.database');
         db.open('userrule');
               
         // Make sure our tables exists
         /*db.execute('drop table if exists Read');
         db.execute('drop table if exists Dismissed');
         db.execute('drop table if exists StoryQueue');
         db.execute('drop table if exists DomainBlacklist');*/      
         
         db.execute('create table if not exists StoryQueue(StoryID int primary key, DateAdded varchar(25))');
         db.execute('create table if not exists Read(StoryID int primary key, DateAdded varchar(25))');
         db.execute('create table if not exists Dismissed(StoryID int primary key, DateAdded varchar(25))');
         db.execute('create table if not exists DomainBlacklist(Domain string primary key, DateAdded varchar(25))');
      }catch(e){
         document.fire('site:nogears');
      }
   }
   this.emptyDB = function(){
      db.execute('delete from StoryQueue');
      db.execute('delete from Read');
      db.execute('delete from Dismissed');
      db.execute('delete from DomainBlacklist');
   }
   
   // can do
   this.canDisplay = function(storyID, domain){
      if (isStoryRead(storyID) || isStoryDismissed(storyID) || oThis.isDomainBlacklisted(domain)){
         return false;
      }else{
         return true;
      }
   }
  
   // story queue
   this.getQueue = function(){
      return getStoryIDs('StoryQueue');
   }
   this.enqueue = function(storyID){
      if (!isStoryInQueue(storyID)){
         db.execute('insert into StoryQueue values (?, ?)', [storyID, dataLayer.getSQLiteDate()]);
         
         if (!isStoryRead(storyID)){
            db.execute('insert into Read values (?, ?)', [storyID, dataLayer.getSQLiteDate()]);
         }
      }
   }
   this.dequeue = function(storyID){
      db.execute('delete from StoryQueue where StoryID = ?', [storyID]);
   }
   this.getRead = function(lastRowID){
      return getStoryIDsByOffset('Read', lastRowID);
   }
   
   // dismiss
   this.dismiss = function(storyID){
      if (!isStoryDismissed(storyID)){
         db.execute('insert into Dismissed values (?, ?)', [storyID, dataLayer.getSQLiteDate()]);
      }
   }
   this.dismissToRead = function(storyID){
      db.execute('delete from Dismissed where StoryID = ?', [storyID]);
      oThis.enqueue(storyID);
   }
   this.getDismissed = function(lastRowID){
      return getStoryIDsByOffset('Dismissed', lastRowID);
   }
   
   // domain blacklist
   this.getDomainBlacklist = function(){
      var domains = [];
      var rs = db.execute('select ROWID, Domain from DomainBlacklist order by DateAdded');
            
      while (rs.isValidRow()) {
         domains.push(dataLayer.createDomainBlacklist(rs.field(0), rs.field(1)));
         rs.next();
      }
      
      rs.close();
      return domains;
   }
   this.addDomainBlacklist = function(domain){
      var id = -1;
      
      domain = domain.strip().toLowerCase();
      
      if (domain.length > 0 && !oThis.isDomainBlacklisted(domain)){
         db.execute('insert into DomainBlacklist values (?, ?)', [domain, dataLayer.getSQLiteDate()]);
         id = db.lastInsertRowId;
      }
      
      return dataLayer.createDomainBlacklist(id, domain);
   }
   this.removeDomainBlacklist = function(id){
      db.execute('delete from DomainBlacklist where ROWID = ?', [id]);
   }
   this.isDomainBlacklisted = function(domain){
      return hasValue('DomainBlacklist', 'Domain', domain);
   }
}
