(function (context, $) {

  "use strict";

  context.JK = context.JK || {};
  context.JK.Stun = function (app) {

    var ALERT_NAMES = context.JK.ALERT_NAMES;
    var logger = context.JK.logger;
    var udp_blocked = null;
    var rest = context.JK.Rest();

    function sync(changed) {

      if(!context.jamClient.NetworkTestResult) return;

      var result = context.jamClient.NetworkTestResult();

      if (udp_blocked === null || (result.remote_udp_blocked != udp_blocked)) {
        // update the server

        if(result.remote_udp_blocked) logger.debug("NO STUN: " + JSON.stringify(result));
        else            logger.debug("STUN capable: " + JSON.stringify(result));

        udp_blocked = result.remote_udp_blocked;

        if (changed) changed(result.remote_udp_blocked)
      }

      return udp_blocked;
    }

    function watch() {
      context.JK.onBackendEvent(ALERT_NAMES.STUN_EVENT, 'everywhere', function () {

        logger.debug("handling stun event...");
        sync(function (blocked) {
          if(app.clientId) {
            rest.updateUdpReachable({client_id: app.clientId, udp_reachable: !blocked})
          }
        });
      });
    }

    function initialize() {
      watch();
    }

    this.initialize = initialize;
    this.sync = sync;
  }

})(window, jQuery);
