/* global APP_CONFIG, SB, App, Player */
/* global $, $$log, $$error */

var AppNetwork = {};

(function() {
    var _requestTimer = null;
    var _disconnectCount = 0;

    sendCheckConnectionRequest();

    function sendCheckConnectionRequest () {
      var url = SB.platformName === 'browser' ?
        APP_CONFIG.CONNECTION_PING_BROWSER_URL : APP_CONFIG.CONNECTION_PING_URL;

      sendPingRequest(url, function (isOk) {
        if (isOk) {
          return onCheckConnectionSuccess({
            nextCheckAfterMs: APP_CONFIG.CONNECTION_PING_INTERVAL_MS
          });
        } else {
          return onCheckConnectionError();
        }
      });
    };

    function onCheckConnectionSuccess(options) {
      if (_disconnectCount >= APP_CONFIG.CONNECTION_ERROR_WHEN_DISCONNECT_COUNT) {
        AppNetwork.onInternetSuccess();
      }
      _disconnectCount = 0;

      setTimeout(sendCheckConnectionRequest, options.nextCheckAfterMs);

      $$log('Connection Request Success.');
    }

    function onCheckConnectionError() {
      _disconnectCount++;

      $$error('Connection Request Failed #' + _disconnectCount);

      if (_disconnectCount < APP_CONFIG.CONNECTION_ERROR_WHEN_DISCONNECT_COUNT) {
        setTimeout(sendCheckConnectionRequest, APP_CONFIG.CONNECTION_ERROR_CHECK_INTERVAL_MS);
        return;
      }

      if (APP_CONFIG.CONNECTION_LOCAL_ENABLED) {
        checkLocalConnection();
      } else {
        AppNetwork.onInternetFail();
      }
    }

    function checkLocalConnection() {
      $$log('Check Local Connection.');

      sendPingRequest(APP_CONFIG.CONNECTION_LOCAL_PING_URL, function (isOk) {
        if (isOk) {
          onCheckConnectionSuccess({
            nextCheckAfterMs: APP_CONFIG.CONNECTION_LOCAL_PING_INTERVAL_MS
          });
        } else {
          AppNetwork.onInternetFail();
        }
      });
    }

    function sendPingRequest(url, callback) {
      var request = new XMLHttpRequest();

      request.open('GET', url, true);

      var oncomplete = function () {
        clearTimeout(_requestTimer);
        callback(isRequestStatusOk(request));
      };

      request.onload = oncomplete;
      request.onerror = oncomplete;

      request.send();

      _requestTimer = setTimeout(function () {
        request.abort();
        callback(false);
      }, APP_CONFIG.CONNECTION_PING_TIMEOUT_MS);
    };

    function isRequestStatusOk(request) {
      if (request && request.status >= 200 && request.status < 300) {
        return true;
      }

      return false;
    }

    $.extend(AppNetwork, {
      onInternetFail: function () {
        setTimeout(sendCheckConnectionRequest, APP_CONFIG.CONNECTION_ERROR_CHECK_INTERVAL_MS);

        if ($('#errors').is(':visible')) {
          return;
        }

        App.error('app_internet_error', function() {
            App.exit();
        });

        try {
          Player.pause();
        } catch (e) {
          $$error(e.message + '. From: OnInternetFail');
        }
      },

      onInternetSuccess: function () {
        _disconnectCount = 0;

        App.closeError();

        try {
          Player.resume();
        } catch (e) {
          $$error(e.message + '. From: onInternetSuccess');
        }
      }
    });
})()
