/* global console */
(function (Twitch, $) {
  var player = {
    hlsId: null
  };

  var p;

  player.init = function (options) {
    // Initializes a single player for this page which can be accessed with Twitch.player.ready
    if (options.type === 'html5') {
      p = new player.HTML5Player(options.html5Options);
      p.init(function () {
        $(Twitch.player).triggerHandler('ready');
      });
    } else {
      // try flash player
      p = new player.FlashPlayer(options.flashOptions);
      p.init(function () {
        $(Twitch.player).triggerHandler('ready');
      },
      function () {
        if (options.type !== 'flash') {
          // fallback to html5
          p = new player.HTML5Player(options.html5Options);
          p.init(function () {
            $(Twitch.player).triggerHandler('ready');
          },
          function (e) {
            p.$el.find('.js-html5-player').hide();
            p.$el.siblings('.js-flash-required').show();
          });
        }
      });
    }
  };

  var _isReady = false;
  $(player).on('ready', function () {
    _isReady = true;
  });
  player.ready = function (callback) {
    // Used to access the player's javascript api
    // Twitch.player.ready(function (player) { ... })
    if (_isReady) {
      callback(p);
    } else {
      $(Twitch.player).on('ready', function () {
        callback(p);
      });
    }
  };

  // todo: delete getPlayer once old player is deprecated
  player.getPlayer = function () {
    console.warn('Twitch.player.getPlayer is deprecated for the new player.');

    if (!p) {
      console.error('Twitch.player.getPlayer called before player is ready.');
    }

    return p;
  };

  player.parseTimeOffset = function (offset) {
    // Takes combinations of hour/min/sec in the format "1h30m10s" and returns
    // the number of seconds corresponding to that time offset
    var match = /^((\d+)[Hh])?((\d+)[Mm])?((\d+)[Ss])?$/.exec(offset || "");
    if (!match) {
      return 0;
    }

    try {
      var hours = parseInt(match[2], 10) || 0,
          minutes = parseInt(match[4], 10) || 0,
          seconds = parseInt(match[6], 10) || 0;

      return (hours * 3600) + (minutes * 60) + seconds;

    } catch (err) {
      return 0;
    }
  };

  // todo: move to FlashPlayer / HTML5Player
  player.setSteamInfo = function (viewerId, broadcasterId) {
    console.warn('Twitch.player.setSteamInfo is deprecated');
    // TODO: display a steam connection notification only on official tournament broadcasters
    // implement this in the player apis
  };

  player.getSpecialOverlay = function () {
    return Twitch.storage.get("adblock_enabled", {storage: 'sessionStorage'}) === "true";
  };

  player.onTwitchPlayerInit = player.onTwitchPlayerLoaded = function (callback) {
    console.warn('Twitch.player.onTwitchPlayer(Init/Loaded) is deprecated! Use Twitch.ready instead.');
    player.ready(callback);
  };

  Twitch.mixin({
    player: player
  });

})(Twitch, jQuery);
