// -*- java -*-
/*
Copyright (c) 2005 Tony Garnock-Jones <tonyg@kcbbs.gen.nz>
Copyright (c) 2005 LShift Ltd. <query@lshift.net>

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

///////////////////////////////////////////////////////////////////////////
// AJAJ - Like AJAX, but using JSON instead of XML.
//
// Instead of using a clumsy alien data language, XML, to communicate
// with the server, we use a data language closer to the built-in
// constructs of JavaScript: JSON. (See http://www.json.org/.)
///////////////////////////////////////////////////////////////////////////

// This AJAJ namespace contains a single function, AJAJ.proxy, which
// constructs a function that dispatches messages to an AJAJ server,
// and a data structure AJAJ.ctors, which is used with our
// "constructors" extension to core JSON in order to deserialize
// exceptions thrown by the server.
//
var AJAJ = {
    ctors: {
	exception: function (arg) { throw arg; }
    },

    // Given the URL of an AJAJ responder service, this function
    // builds and returns a function which packages its argument,
    // sends it to the service, and when a reply is received calls one
    // of the two continuations passed in.
    //
    // url: the URL of the AJAJ service
    //
    // arg: the datum to encode using JSON and transmit to the server
    // ksucc: a function to call if the request succeeds.
    //        ksucc will be invoked with the deserialized JSON object
    //        returned by the service.
    // kfail: a function to call if the request fails.
    //        kfail will be invoked with the detail of the request failure.
    //
    proxy: function (url) {
	return function (arg, ksucc, kfail) {
	    new Ajax.Request(url, {
		    postBody: JSON.stringify(arg),
		    onSuccess: function (transport) {
				 var result;
				 try {
				     result = JSON.parse(transport.responseText, AJAJ.ctors);
				   try {
				     if (ksucc) {
				       ksucc(result);
				     }
				   } catch (e) {
				     alert("Died in onSuccess: " + JSON.stringify(e));
				   }
				 } catch (e) {
				   if (kfail) {
				     kfail({message: "Died parsing response from AJAJ server",
					       name: "AJAJResponseParseError",
					       arg: arg,
					       url: url,
					       inner: e});
				   }
				 }
			       },
		    onFail: function (transport) {
			      if (kfail) {
				kfail({message: "AJAJ request failed",
				       name: "AJAJFailure",
				       arg: arg,
				       url: url,
				       transport: transport});
			      }
			    }
		});
	};
    }
};

// This class is a clone of prototype.js's PeriodicalExecuter, made to
// remedy a deficiency in the prototype.js code. PeriodicalExecuter
// has no way of halting the callback loop, which might be something a
// client would want to do, for instance if some fatal error occurs.
//
// Ideally we'd be able to subclass or otherwise modify
// PeriodicalExecuter directly - but the way the code is currently
// structured prevents that. Instead I've taken a snapshot of
// PeriodicalExecuter, and made the minimum change needed to add a
// working stop() method.
//
var StoppablePeriodicalExecuter = Class.create();
StoppablePeriodicalExecuter.prototype = {
  initialize: function(callback, frequency) {
    this.callback = callback;
    this.frequency = frequency;
    this.currentlyExecuting = false;
    this.intervalHandle = null;

    this.registerCallback();
  },

  registerCallback: function() {
    this.intervalHandle = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  stop: function() {
    if (this.intervalHandle != null) {
      clearInterval(this.intervalHandle);
    }
  },

  onTimerEvent: function() {
    if (!this.currentlyExecuting) {
      try { 
        this.currentlyExecuting = true;
        this.callback(this);
      } finally { 
        this.currentlyExecuting = false;
      }
    }
  }
};
