/*   ___           ___           ___           ___           ___           ___     
    /\  \         /\  \         /\__\         |\__\         /\  \         /\__\    
   /::\  \       /::\  \       /:/  /         |:|  |       /::\  \       /::|  |   
  /:/\:\  \     /:/\:\  \     /:/  /          |:|  |      /:/\:\  \     /:|:|  |   
 /::\~\:\  \   /::\~\:\  \   /:/  /  ___      |:|__|__   /::\~\:\  \   /:/|:|__|__ 
/:/\:\ \:\__\ /:/\:\ \:\__\ /:/__/  /\__\ ____/::::\__\ /:/\:\ \:\__\ /:/ |::::\__\
\/__\:\ \/__/ \/__\:\/:/  / \:\  \ /:/  / \::::/~~/~    \/_|::\/:/  / \/__/~~/:/  /
     \:\__\        \::/  /   \:\  /:/  /   ~~|:|~~|        |:|::/  /        /:/  / 
      \/__/        /:/  /     \:\/:/  /      |:|  |        |:|\/__/        /:/  /  
                  /:/  /       \::/  /       |:|  |        |:|  |         /:/  /   
                  \/__/         \/__/         \|__|         \|__|         \/__/ 
    
    FauxRM, a Really Simple Data Persistence Thingo for HTML5
    -- omygawshkenas
*/

FauxRM = {
  
  // Sets up a connection to a data-store.
  // options : name, version, display_name, size (in bytes)
  setup : function(options) {
    var opts = { name : 'FauxRM', version : '1.0', display_name : '', size : 2000000 };
    Object.extend(opts, options);
    FauxRM.db = openDatabase(opts.name, opts.version, opts.display_name, opts.size);
    FauxRM.db.transaction(function(tx) {
      tx.executeSql("select count(*) from faux_rm_models", [], function(result) {
        // All set, the table exists.
      }, function(tx, error) {
        tx.executeSql("create table faux_rm_models (id string unique, class string, data text, created_at integer, updated_at integer, synced_at integer)", [], function(result) {
          // All set, the table was created.
        });
      });
    });
  },
  
  // Makes a new FauxRM Model class
  model : function(model, options) {
    var newModel = eval(model + " = Class.create({})");
    newModel.klass = model;
    newModel.options = options || {};
    Object.extend(newModel, FauxRM.Model.ClassMethods);
    Object.extend(newModel, Enumerable);
    Object.extend(newModel.prototype, FauxRM.Model.InstanceMethods);
    newModel.prototype.klass = model;
    newModel.data = {};
  }
};


FauxRM.Model = {
    
  ClassMethods : {
    
    // Load all of the model's objects from the database
    load : function(callback) {
      var self = this;
      FauxRM.db.transaction(function(tx) {
        tx.executeSql("select * from faux_rm_models where class = ?", [self.klass], function(tx, result) {
          for (var i = 0; i < result.rows.length; ++i) {
            var row = result.rows.item(i);            
            var obj = new top[self.klass]();
            var data = row.data.evalJSON();
            delete obj['_notYetSaved'];
            obj.data = data;
            obj.id = row.id;
            obj.createdAt = row.created_at;
            obj.updatedAt = row.created_at;
            self.data[row.id] = obj;
          }
          callback();
        });
      });
    },
    
    // Find a model, based on an id
    get : function(id) {
      return this.data[id];
    },
    
    // Loop through each model.
    _each : function(fun) {
      this.values().each(fun);
    },
    
    // Get the size of the pool.
    size : function() {
      return $H(this.data).size();
    },
    
    // Return the first element (usually for testing)
    first : function() {
      return this.values().first();
    },
    
    // Returns the ids of all the models.
    ids : function() {
      return $H(this.data).keys();
    },
    
    values : function() {
      var values = $H(this.data).values();
      if (!this.options.order) return values;
      return values.sortBy(function(value){ return value.get(this.options.order) || 0; }.bind(this));
    }
    
  },
  
  InstanceMethods : {
    
    // You can initialize a new Model with optional arbitrary data and an id.
    // If you do not provide an id, a UUID will be assigned.
    initialize : function(data, id) {
      this.data = data || {};
      this.id = id || uuid();
      this._notYetSaved = true;
      this.updatedAt = this.createdAt = (new Date()).getTime();
    },
    
    // Look up a data property.
    get : function(key) {
      return this.data[key];
    },
    
    // Set a data property.
    set : function(key, value) {
      this.updatedAt = (new Date()).getTime();
      this.data[key] = value;
      return this;
    },
    
    // Mass assign properties.
    setAll : function(data) {
      $H(data).each(function(key, value) {
        this.set(key, value);
      }.bind(this));
      return this;
    },
    
    // Create or save this model to the database.
    save : function() {
      var self = this;
      top[self.klass].data[self.id] = self;
      var data = this.toJSON();
      if (self._notYetSaved) {
        FauxRM.db.transaction(function(tx) {
          tx.executeSql('insert into faux_rm_models (id, class, data, created_at, updated_at) values (?, ?, ?, ?, ?)', [self.id, self.klass, data, self.createdAt, self.updatedAt], null, function(code, mess){alert(mess);});
        });
        delete self['_notYetSaved'];
      } else {
        FauxRM.db.transaction(function(tx) {
          tx.executeSql('update faux_rm_models set data = ?, updated_at = ? where id = ?', [data, self.updatedAt, self.id], null, function(code, mess){alert(mess);});
        });
      }
      return true;
    },
    
    // Remove this from from the database
    destroy : function() {
      var self = this;
      var classHash = $H(top[this.klass].data);
      classHash.unset(this.id);
      top[this.klass].data = classHash.toObject();      
      if (self._notYetSaved) return true;
      FauxRM.db.transaction(function(tx) {
        tx.executeSql('delete from faux_rm_models where id = ?', [self.id], null, function(code, mess){alert(mess);});
      });
    },
    
    // Convert the model's data to JSON.
    toJSON : function() {
      return Object.toJSON(this.data);
    }
    
  }
};


//////////////////////////////////////////////////////
//  Extensions below this point.
//////////////////////////////////////////////////////


/*
UUID.js
Copyright (c) 2008, Robert Kieffer
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of Robert Kieffer nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/**
 * Generate a random uuid.  If 'len' is unspecified or zero then an RFC 4122
 * (version 4) UUID is created, otherwise the the uuid will consist of 'len'
 * characters, each of which is randomly choosen from the set of [0-9A-Za-z].
 *
 * For example:
 *   >>> randomUUID()
 *   "92329D39-6F5C-4520-ABFC-AAB64544E172"
 *   >>> randomUUID(10)
 *   "KI4Ed4ctHq"
 */
function uuid(len) {
  var uuid = [], me = arguments.callee, c = me.chars;
  if (!c) c = me.chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''); 

  if (len) {
    // Compact uuid form
    for (var i = 0; i < len; i++) uuid[i] = c[0 | Math.random()*62];
  } else {
    var ri=0, r;

    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
    uuid[14] = '4';

    for (var i = 0; i < 36; i++) {
      if (uuid[i]) continue;
      r = 0 | Math.random()*16;
      // i==19: set the high bits of clock sequence as per rfc4122, sec. 4.1.5
      uuid[i] = c[(i == 19) ? (r & 0x3) | 0x8 : r & 0xf];
    }
  }

  return uuid.join('');
}