/**
 * WebSampConnector Toolkit.
 * 
 * This file contains the WebSampConnector handlers which allow your Web application
 * to handle messages with registered VO-softwares. You are encouraged to override these 
 * methods to fulfill the requirements of your Web application.
 * @requires websampconnector.js
 * @see http://vo.imcce.fr/webservices/samp/?manual 
 * @author J. Berthier <berthier@imcce.fr> (IMCCE/OBSPM/VOParis Data Centre)
 * @author A. Tregoubenko <http://arty.name>
 * @version 1.5, 2010-03-13
 * @copyright 2010, VO-Paris Data Centre <http://vo.obspm.fr/>
 */

(function() {
   
   // Check if the namespace is defined
   if (typeof WebSampConnector == "undefined") {
      throw new Error("Error: WebSampConnector Handlers: The WebSampConnector namespace is undefined.\nLoad websampconnector.js before this script.");
   }

   // Default id of the html img element of the status icon
   iconId = 'hubStatusIcon';
   // Default prefix of the hub status icon names (e.g. icons/hub-)
   iconPrefix = 'icons/hub-';
   // Default extension of the hub status icon filename
   iconExt = '.png';

   /*
    * Client configuration method to override default configuration values of the status icon
    */
   WebSampConnector.configureStatusIcon = function(options) {
      this.iconId     = options.iconId     || this.iconId;
      this.iconPrefix = options.iconPrefix || this.iconPrefix;
      this.iconExt    = options.iconExt    || this.iconExt;
   };

   /* 
    * This method display the given icon image
    * @param string the filename of the status icon
    */
   WebSampConnector.setStatusIcon = function(icon) {
      var iconId = document.getElementById(this.iconId);
      if (iconId) {
         iconId.src = icon;
      }
   };

   /*
    * This method changes the icon which indicates the status of the connection to the hub.
    * It is the default callback function. If you provide your own callback function, do
    * not forget to define the corresponding binding (see the end of this file).
    * @param status Hub status string: connected, disconnected, unknown
    */
   WebSampConnector.updateStatusIcon = function(status) {
      var iconId = document.getElementById(this.iconId);
      if (iconId) {
         iconId.src = this.iconPrefix + status + this.iconExt;
      }
   };

   /*
    * Default callback function: this function will be called by the Java applet as soon
    * as the connection is established and is ready to handle events
    */
   WebSampConnector.onlineHandler = WebSampConnector.updateStatusIcon;
   
   /*
    * This method allows the client to know if he's connected or not to the running hub.
    */
   WebSampConnector.getConnectionStatus = function() {
      try {
         if (WebSampConnector.isConnected()) {
            alert('Connected');
         } else {
            alert('Not connected');
         }
      } catch (e) {
         WebSampConnector.log('WebSampConnector.getConnectionStatus:\n' + e);
      }
   };

   /*
    * This method unregisters the client and terminates the connection
    */
   WebSampConnector.disconnectHub = function() {
      try {
         if (WebSampConnector.disconnect()) {
            WebSampConnector.updateStatusIcon("disconnected");
         } else {
            alert("OOOPS!");
         }
      } catch (e) {
         WebSampConnector.log('WebSampConnector.disconnectHub:\n' + e);
      }
   };

   /*
    * This method allows the client to know which clients are registered (mtype="")
    * or which clients have subscribed a given MType (mtype!="")
    * @param mtype the given MType (e.g. table.load.votable)
    */
   WebSampConnector.getClients = function(mtype) {
      try {
         var applet = WebSampConnector.getApplet();
         if (mtype.length > 0) {
            var clients = WebSampConnector.getSubscribedClients(new Array(mtype));
            var textn = "Subscribed clients of MType: " + mtype + "\n";
         } else {
            var clients = WebSampConnector.getRegisteredClients();
            var textn = "Registered clients:\n";
         }
         for (i=0; i<clients.length; i++) {
            textn += ' * Id: ' + clients[i].id + '\n' 
                    + '  - Name: ' + clients[i].name + '\n' 
                    + '  - Description: ' + clients[i].descriptionText + '\n';
         }
         alert(textn);
      } catch (e) {
         WebSampConnector.log('WebSampConnector.getClients:\n' + e);
      }      
   };

   /*
    * Private method
    * Formats a number in a sexagesimal representation (e.g. deg:min:sec)
    * @param num a decimal number
    * @return a string containing the sexagesimal representation of the number 
    */
   WebSampConnector.decToSexa = function(num) {
      var deg = parseInt(num);
      num -= deg;
      num *= 60;
      var min = parseInt(num);
      num -= min;
      num *= 60;
      var sec = parseInt(num);
      return '' + deg + ':' + min + ':' + sec;
   };

   /*
    * Private method
    * Formats a number in a decimal representation (e.g. xx.xxx)
    * @param sexa a sexagesimal representation (e.g. deg:min:sec)
    * @return a string containing the decimal representation of the input 
    */
   WebSampConnector.sexaToDec = function(sexa) {
      var parts = sexa.split(':');
      return 3600 * parts[0] + 60 * parts[1] + 1 * parts[2];
   };

   // Default id of the HTML element which display the events broadcasted by VO-applications
   handlerId = 'HubMsg';

   /*
    * Client configuration method to override the default id of the HTML element 
    * which display the events broadcasted by VO-applications.
    */
   WebSampConnector.setHandlerId = function(id) {
      this.handlerId = id || this.handlerId;
   };

   /*
    * Returns the id of the HTML element which display the events broadcasted by VO-applications.
    */
   WebSampConnector.getHandlerId = function() {
      return this.handlerId;
   };

   /*
    * This method allows a VO application to point a given celestial coordinate in the Web page
    * @param args an array which contains the celestial coordinates: RA=args[0], DEC=args[1]
    * TODO: describe parameters better
    */
   WebSampConnector.pointAtSkyHandler = function(ra, dec) {
      var textn = "RA=" + WebSampConnector.decToSexa(ra) + " ; DEC=" + WebSampConnector.decToSexa(dec);
      var handler = document.getElementById(this.handlerId);
      if (handler) {
         handler.value = textn;
      }
   };
    
   /*
    * This method allows a VO application to highlight a given row in the Web page
    * @param tableId Celestial coordinates: tableId
    * @param url Celestial coordinates: url
    * @param row Celestial coordinates: row
    * TODO: describe parameters better
    */
   WebSampConnector.highlightRowHandler = function(tableId, url, row) {
      var textn = "Highlighted row: #" + row;
      var handler = document.getElementById(this.handlerId);
      if (handler) {
         handler.value = textn;
      }
   };
    
   /*
    * This method allows a VO application to highlight a selection of rows in the Web page
    * @param tableId Celestial coordinates: tableId
    * @param url Celestial coordinates: url
    * @param rows Celestial coordinates: rows // NB: this parameter should be an array
    * TODO: describe parameters better
    */
   WebSampConnector.selectRowListHandler = function(tableId, url, rows) {
      var textn = "Selected rows: ";
      for (var i=0; i<rows.length; i++) {
         textn += '#' + rows[i] + ', ';
      }
      var handler = document.getElementById(this.handlerId);
      if (handler) {
         handler.value = textn;
      }
   };
   
})();

