/*
 * Copyright 2006 OST-SYSTEMS. All rights reserved.
 */

function ServerStorage(path, callback, loadingIcon) {
  this.path = path;
  this.callback = callback;
  this.loadingIcon = loadingIcon;
  this.fifo = new Array();
  this.sending = false;
  this.reloadFilter = null;
  
  this.storeInternal = function(group, id, key, value) {
    KeyStorage.prototype.store.call(this, group, id, key, value);
  }
  
  this.removeAllInternal = function(group, id) {
    KeyStorage.prototype.store.call(this, group, id);
  }
  
  this.send = function() {
	  if (this.fifo.length == 0) {
	    return;
	  }
	  if (this.fifo.length > 1) {
	    this.sendMulti();
	    return;
	  }
	  this.sending = true;
	  var request = createXMLHttpRequest();
	  var group = this.fifo[0][0];
	  var id = this.fifo[0][1];
	  var key = this.fifo[0][2];
	  var value = this.fifo[0][3];
	  var command = "store";
	  if (key == null) {
	    command = "removeAll"
	  }
	  var content = "command=" + command + "&class=" + escape(group);
	  if (id != null) {
	    content += "&id=" + escape(id);
	    if (key != null) {
	      content += "&key=" + escape(key);
	      if (value != null) {
	        content += "&value=" + escape(value);
	        if (value.length > 1024) {
	          parent.addError("Storage Value is bigger than 1k: " + content);
	        }
	      }
	    }
	  }
	  //alert("Send " + this.fifo.length + " " + url);
	  var url = this.path;// + "?" + content; 
	  request.open("POST", url, true);
	  request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	  var _self = this;
	  request.onreadystatechange = function() {
  	  if (request.readyState == 4) {
  	    _self._storeOnLoad(request);
  	  }  
	  }  
	  request.send(content);
	  //alert("Sent " + this.sending);  
  }
  
  this.sendMulti = function() {
	  this.sending = true;
	  var request = createXMLHttpRequest();
	  var command = "storeMulti";
	  var group = this.fifo[0][0];
	  var id = this.fifo[0][1];
	  var key = this.fifo[0][2];
	  var value = this.fifo[0][3];
	  var content = "command=" + command + "&count=" + this.fifo.length;
	  for (var i = 0; i < this.fifo.length; i++) {
  	  content += "&class" + i + "=" + escape(this.fifo[i][0]);
  	  if (this.fifo[i][1] != null) {
  	    content += "&id" + i + "=" + escape(this.fifo[i][1]);
  	    if (this.fifo[i][2] != null) {
  	      content += "&key" + i + "=" + escape(this.fifo[i][2]);
      	  var value = this.fifo[i][3];
  	      if (value != null) {
  	        content += "&value" + i + "=" + escape(value);
  	        if (value.length > 1024) {
  	          parent.addError("Storage Value is bigger than 1k: " + content);
  	        }
  	      }
  	    }
  	  }	  	
	  }
	  //alert("Send " + this.fifo.length + " " + url);
	  var url = this.path;// + "?" + content; 
	  request.open("POST", url, true);
	  request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	  var _self = this;
	  var count = this.fifo.length;
	  request.onreadystatechange = function() {
  	  if (request.readyState == 4) {
  	    _self._storeMultiOnLoad(request, count);
  	  }  
	  }  
	  request.send(content);
	  //alert("Sent " + this.sending);  
  }
  
  this._doRequest = function(command, params, callback) {
	  var request = createXMLHttpRequest();
	  var url = this.path + "?command=" + command;
	  if (params != null) {
  	  for (var key in params) {
	      url += "&" + escape(key) + "=" + escape(params[key]);
	    }
	  }  
	  request.open("GET", url, true);
	  var self = this;
	  request.onreadystatechange = function() {
  	  if (request.readyState == 4) {
  	    if (self.loadingIcon) {  	    
  	      self.loadingIcon.style.visibility = "hidden";  
  	    }  
	      callback(self, request);
  	  }  
	  }
	  if (this.loadingIcon) {
	    this.loadingIcon.style.visibility = "visible";
	  }  
	  try {
	    request.send(null);  
	  }
	  catch (e) {
  	  if (this.loadingIcon) {
  	    this.loadingIcon.style.visibility = "hidden";  
  	  }  
	    self.callback("loginFailed");
	  }  
  }
  
  this._storeOnLoad = function(request) {
    if (request.status == 200) {
      var status = eval(request.responseText);
      if (status != "success") {
        this.callback(status);
    	  //alert(this.sending);
        return;
      }
      this.fifo.shift();
      //alert("Check Fifo: " + this.fifo.length);
      if (this.fifo.length > 0) {
        this.send();
        return;
      }
    }
	  this.sending = false;
	  //alert(this.sending + " " + request.responseText);
  }
  
  this._storeMultiOnLoad = function(request, count) {
    if (request.status == 200) {
      var status = eval(request.responseText);
      if (status != "success") {
        this.callback(status);
    	  //alert(this.sending);
        return;
      }
      for (var i = 0; i < count; i++) {
        this.fifo.shift();      	
      }
      //alert("Check Fifo: " + this.fifo.length);
      if (this.fifo.length > 0) {
        this.send();
        return;
      }
    }
	  this.sending = false;
	  //alert(this.sending + " " + request.responseText);
  }
  
  this._loginOnLoad = function(_self, request) {
    if (request.status == 200) {
      var status = eval(request.responseText);
      if (!status) {
        _self.callback("loginFailed");
      }
      else {
        _self.reload();
      }
    }
  }

  this._newUserOnLoad = function(request) {
    if (request.status == 200) {
      var status = eval(request.responseText);
      if (!status) {
        this.callback("newUserFailed");
      }
      else {
        this.callback("newUser");
      }
    }
  }

  this._reloadOnLoad = function(self, request) {
    if (request.status == 200) {
      var status = eval(request.responseText);
      if (status == "success" && result != null) {
        widgetsHelper.clearList();
        for (var i = 0; i < result.length; i++) {
          self.storeInternal(result[i][0], result[i][1], result[i][2], result[i][3]);          
        }
        self.callback("login");
      }
      else {
        self.callback(status);
      }
    }
  }

  this._logoutOnLoad = function(request) {
    if (request.status == 200) {
      var status = eval(request.responseText);
      if (!status) {
        this.callback("logoutFailed");
      }
    }
  }

  this._removeUserOnLoad = function(request) {
    if (request.status == 200) {
      var error = null;
      var status = eval(request.responseText);
      if (status != "success") {
        this.callback(status);
      }
      if (error != null && error == "Developer") {
        alert("Developer accounts can't be removed.");
      }
    }
  }

  this._removeAllOnLoad = function(request) {
    if (request.status == 200) {
      var status = eval(request.responseText);
      if (status != "success") {
        this.callback(status);
        return;
      }
    }
  }

}

ServerStorage.prototype = new KeyStorage();

ServerStorage.prototype.saveAll = function() {
}

ServerStorage.prototype.reload = function() {
  this._doRequest("retrieveAll", this.reloadFilter, this._reloadOnLoad);
}

ServerStorage.prototype.login = function(user, password) {
  var params = new Object();
  params.name = user;
  params.password = password;
  this._doRequest("login", params, this._loginOnLoad);
}

ServerStorage.prototype.newUser = function(user, password) {
  var request = createXMLHttpRequest();
  request.open("GET", this.path + "?command=signIn&name=" + escape(user)
    + "&password=" + escape(password), true);
  var _self = this;
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      _self._newUserOnLoad(request);
    }  
  }  
  request.send(null);  
}

ServerStorage.prototype.logout = function() {
  var request = createXMLHttpRequest();
  request.open("GET", this.path + "?command=logout", true);
  var _self = this;
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      _self._logoutOnLoad(request);
    }  
  }  
  request.send(null);  
}

ServerStorage.prototype.removeUser = function() {
  var request = createXMLHttpRequest();
  request.open("GET", this.path + "?command=removeUser", true);
  var _self = this;
  request.onreadystatechange = function() {
 	  if (request.readyState == 4) {
      _self._removeUserOnLoad(request);
 	  }  
  }  
  request.send(null);  
}

ServerStorage.prototype.store = function(group, id, key, value) {  
  this.storeInternal(group, id, key, value);
  this.fifo.push(new Array(group, id, key, value));
  if (!this.sending) {
    this.send();
  }  
}

ServerStorage.prototype.sendAll = function() {
  var storage = this.getStorage();
  for (var group in storage) {
    for (var id in storage[group]) {
      for (var key in storage[group][id]) {
		    this.fifo.push(new Array(group, id, key, storage[group][id][key]));
      }
    }
  }
  if (!this.sending) {
   	this.send();
	}  
}

ServerStorage.prototype.removeAll = function(group, id) {
  this.removeAllInternal(group, id);
  this.fifo.push(new Array(group, id, null, null));
  if (!this.sending) {
    this.send();
  }  
}  

