/*
 * Ce module permet d'écouter la blockchain
 * Il maintient un tableau de hooks
 * Il vérifie l'existence d'un nouveau block toutes les 30s
 * Si un nouveau block est détecté, les hooks sont lancés un par un
 */
blockchainListener = function(){

  var _last_block       = null;
  var _last_block_hooks = [];
  
  function _logBlockHash(leblock, flag)
  {
    if (flag) return "logBlockHash";
    topistoConsole.log('Last Block detected : '+leblock.hash);
  };

  function _isBlockNew(leblock)
  {
    return ((_last_block == null)||(_last_block.hash != leblock.hash));
  };
  
  function _lastBlockTrigger()
  {
    $.get( "data/getBlockInfo.php", function( data ) {
      if (_last_block_hooks.length > 0)
      {
        if (_isBlockNew(data))
        {
          if (_last_block = data != null)
          {
            _last_block_hooks.forEach(function(trigger) {
              if (trigger instanceof Function) trigger(data);
            });
          }
          _last_block = data;
        } 
      }
    }, "json" );
  };

  function _addBlockHook(addBlockHook){
    var hookname = addBlockHook(null, true);
    var flag_add = false;
    _last_block_hooks.forEach(function(trigger) {
      if (trigger instanceof Function)
      {
        var local_hookname = trigger(null, true);
        flag_add = flag_add || (local_hookname == hookname);
      }
    });    
    if (!flag_add) _last_block_hooks.push(addBlockHook);
  };

  function _init(){
    _addBlockHook(_logBlockHash);
    setInterval(_lastBlockTrigger, 30000);
  };

  return {init: _init, addBlockHook: _addBlockHook};
}();

$(document).ready(function() {
  blockchainListener.init();
});
