/*jshint maxlen:123 */

(function (Twitch, $) {

  var ACCESS_TOKEN_URL_TEMPLATE = '/api/channels/{{channel}}/access_token';
  var USHER_M3U8_URL_TEMPLATE = '//usher.ttvnw.net/api/channel/hls/{{channel}}.m3u8?token={{{token}}}&sig={{{sig}}}';

  var hls = {};

  hls.getPlaylist = function (channelName) {
    return new RSVP.Promise(function (resolve, reject) {
      if (!channelName || !channelName.length) return reject();
      Twitch.api.get(ACCESS_TOKEN_URL_TEMPLATE.replace('{{channel}}', encodeURIComponent(channelName)))
      .then(function (response) {
        if (response.token && response.sig) {
          resolve(USHER_M3U8_URL_TEMPLATE.replace('{{channel}}', encodeURIComponent(channelName))
            .replace('{{{token}}}', response.token)
            .replace('{{{sig}}}', response.sig));
        } else {
          reject();
        }
      }, reject);
    });
  };

  Twitch.mixin({
    hls: hls
  });

})(Twitch, jQuery);
