dojo.provide("parus.userdata");

dojo.require("parus.parus8");
dojo.require("parus.database");
dojo.require("parus.xml");

if (!parus) parus = {};

if (!parus.userdata) dojo.mixin(parus, {
  userdata: {}
});

dojo.mixin(parus.userdata, {

  _store: null,

  _signature: "version 1.0.0.0",

  _timeoutID: null,

  load: function() {
    var data = {};

    nodes = parus.parus8.rowNodes(parus.database.execute("GetUserData", {}))[0];
    if (nodes) {
      nodes = nodes.firstChild;
      if (nodes) {
        nodes = nodes.firstChild;
        if (nodes) {
          nodes = nodes.childNodes;
          if (nodes) for (var i = 0; i < nodes.length; i++) data[nodes[i].nodeName] = nodes[i].firstChild.nodeValue;
        }
      }
    }
    this._store = (data["_signature"] == this._signature) ? data : {};
  },

  _extractIdent: function(key) {
    return key.replace(/[^a-zA-Z0-9_\-\.]/g, "");
  },

  get: function(key) {
    try {
      return this._store ? dojo.fromJson(this._store[this._extractIdent(key)] || "{}") : {};
    }
    catch (e) {
      return {};
    };
  },

  set: function(key, value, immediate) {
    if (!this._store) return;
    this._store["_signature"] = this._signature;
    var obj = this.get(key);
    dojo.mixin(obj, value);
    this._store[this._extractIdent(key)] = dojo.toJson(obj);
    if (this._timeoutID) clearTimeout(this._timeoutID);
    this._timeoutID = setTimeout(dojo.hitch(this, function() {
      this._timeoutID = null;
      parus.database.execute("SetUserData", {
        blobDATA: {
          DATA: dojo.clone(this._store)
        }
      }, function() {});
    }), immediate ? 1 : 6000);
  },

  cleanUp: function() {
    this._store = {
      "_signature": this._signature
    };
    if (this._timeoutID) clearTimeout(this._timeoutID);
    this._timeoutID = null;
    parus.database.execute("SetUserData", {
      blobDATA: {
        DATA: dojo.clone(this._store)
      }
    });
  },

  spread: function(rns) {

    this._store["_signature"] = this._signature;
    if (this._timeoutID) clearTimeout(this._timeoutID);
    if (this._timeoutID) clearTimeout(this._timeoutID);
    this._timeoutID = null;
    parus.database.execute("SpreadUserData", {
      blobDATA: {
        DATA: dojo.clone(this._store)
      },
      RN: rns.join(";")
    });
  }

});