/*jshint bitwise: false*/
/* global Minixperiment, RSVP, console, cookie, SiteOptions */
(function (Twitch, $) {
  /* TODO: Refactor to use Service Provider rather than SiteOptions.experiments
     https://git-aws.internal.justin.tv/common/minixperiment-client-js#serviceprovider */
  var EXPERIMENTS_CONFIG = SiteOptions.experiments || {},
      EXPERIMENTS_UUID_MAP = {
        'BROWSE_EXPERIMENT': '99494f77-1c7c-46c5-9b9c-a117db47d3c5',
        'RECOMMENDED_CHANNELS': 'aaac75ea-c969-4826-b32d-ceefac620a79',
        'RECOMMENDED_GAMES': '61b169ff-bc62-4725-a40e-1be627197c6f',
        'VODS_GAME_INFO': 'ac39b897-d41d-4255-90b6-3a59027e12e0',
        'VOD_COVIEWS': 'c48ae3e6-1356-4ccc-8fbe-12c6909f9e98',
        'VOD_COVIEWS_AB': 'e7516730-b94f-4d46-894e-c18612aab270',
        'VOD_COVIEWS_FORCED_VARIETY': '2f8210be-a6c6-43b1-9f6a-4b7cc7ef93c0',
        'VOD_COVIEWS_SHUFFLE': '403707e6-abb9-401c-a2ca-dd643293dbdd',
        'VOD_UPLOAD_UNITS': '1e406d0d-c293-4c4e-812f-049db8c7e3ec',
        'SIMILAR_VODS': 'b3dbd888-3ed2-4129-a6a9-7ad4c3d866d7',
        'CDN_EXPERIMENT': 'b29d055f-74f2-40b9-9383-9c4b79b30360',
        'CREATIVE_UNLIKELY_HERO': 'dd2d60cd-b76b-4beb-a38c-ea60df88b3cc',
        'CREATIVE_DIRECTORY_CVS': '36a0e500-f117-41dd-8421-3e3db7d567dd',
        'CREATIVE_SIDEBAR_NAVIGATION': 'f60b889e-0327-46a8-ad7b-0d402717da45',
        'CSGO_LANGUAGE_SAMPLE': 'b86f6c73-d333-4d80-ab45-07cfff39aede',
        'VOD_PAGE_RECOMMENDATION_ORDER': '171906a2-6e34-4d0e-879c-a76a19f19097',
        'REMOVE_CSGO_DIRECTORY': '355ff3e2-38b5-449a-8ab8-a52b5d3ab817',
        'LANGUAGE_DIRECTORY_FILTER': '653cc0db-d332-4df6-b224-15c5c481f7e7',
        'LANGUAGE_DIRECTORY_ROWCOUNT': '8a557906-5bfd-4790-b26c-cda8209567a7',
        'CHANNEL_VIDEOS_TAB': '852b3485-a831-4580-b7bf-acf819977704',
        'MESSAGE_DELETED_EXPERIMENT': '04165981-17be-4593-afbd-762a380f6838',
        'RESUME_WATCHING_BANNER': '4f5c0aa5-292d-4ed3-9b2a-f9da6ea195f2',
        'CHAT_RULES_EXPERIMENT' : '98f3f2a5-9e4e-4ba8-aabe-2ff85e7309ee',
        'ESL_CSGO_STEAM_LINK': '6a857f53-de28-4025-8983-3cada70538cd',
        'CHANNEL_PAGE_REDESIGN': '3ae835b6-3015-440c-8177-755bdbbbf29e',
        'MESSAGE_HISTORY': '8ace0f50-8afd-424a-a086-3e61b3e66da0',
        'BITS_FOR_ADS': '2c1c9b8c-530c-4011-a2a0-e93c0e14d8c2',
        'NEXUS_ROLLOUT': '428d3b07-cc7a-424f-aad0-971f5415879a',
        'DETERMINATION': 'cc164e1e-1361-4730-8d9b-0091a0f9cb8f',
        'WATCH_NOW_RIGHTBAR': '5380a8cf-e5cf-497e-9c6c-16cb1c881e0c',
        'CHANNEL_LOGIN_CTA': 'aece7525-dceb-49ba-af1b-242c1ae45831',
        'DISCOVER_SHOW_COVIEWS': '3e011e23-ef29-46a5-af4b-a86e15d8c9e6',
        'PERPETUA': 'af8f152a-f618-416e-8b79-d6ac30479018',
        'EXTENSIONS': '264f75af-a787-4a40-8654-40d78b4d8b41',
        'INTL_I18N': '0670f0ea-3b5c-41a8-946d-114ef4a42540',
        'DISCOVER_HIDE_RECENTLY_WATCHED_STREAMS': '95869c70-08ce-4e58-a82e-bcaaaf1f8dc2',
        'CLIENT_BATCH_SPADE': '1b905261-e257-4703-ac84-12a6a9099935',
        'CLIENT_BATCH_MIXPANEL': '42f5eea6-c548-4791-b767-9c7e29b73ef6',
        'CLIPS_FEEL_IT_COMING': '2858bc04-3f98-4808-a2dd-86555885ca90',
        'CLIPS_HEAR_ME_NOW': '9649684c-6d3f-423d-9d3c-f4296efee975',
        'ONSITE_NOTIFICATIONS': 'b2925d54-cebb-4e1d-a50d-9dd2b1ea850e',
        'NEWS_FEED_REDESIGN': '05d8869f-e037-4955-b80a-7c361f9ddffb',
        'VOD_UPLOAD_UNITS_V3': '1710cf57-352c-4d09-b2c1-3d40bdf79b30',
        'CHOMPY': '9b0cc0db-f52c-435f-832d-ba5ac5fc1d57',
        'ADOPT': '5397de92-0538-42d1-977c-11842e03c9e5',
        'SNAIL': 'fc494cf9-3a22-448e-b262-ba9e218559e5',
        'ORC': 'd4d938f7-bdc2-42cd-afd0-f434e4192c29',
        'LANGUAGE_DIRECTORY_ROWCOUNT_V2': '8d2e5bd8-c305-455f-b7ff-ca6fc2ea8710'
      },
      EXPERIMENT_DEFAULTS = {
        '99494f77-1c7c-46c5-9b9c-a117db47d3c5': 'control', // BROWSE_EXPERIMENT
        'aaac75ea-c969-4826-b32d-ceefac620a79': 'no', // RECOMMENDED_CHANNELS
        '61b169ff-bc62-4725-a40e-1be627197c6f': 'no', // RECOMMENDED_GAMES
        'ac39b897-d41d-4255-90b6-3a59027e12e0': 'control', // VODS_GAME_INFO
        'c48ae3e6-1356-4ccc-8fbe-12c6909f9e98': 'control', // VOD_COVIEWS
        'e7516730-b94f-4d46-894e-c18612aab270': 'control', // VOD_COVIEWS_AB
        '2f8210be-a6c6-43b1-9f6a-4b7cc7ef93c0': 'control', // VOD_COVIEWS_FORCED_VARIETY
        '403707e6-abb9-401c-a2ca-dd643293dbdd': 'control', // VOD_COVIEWS_SHUFFLE
        '1e406d0d-c293-4c4e-812f-049db8c7e3ec': 'control', // VOD_UPLOAD_UNITS
        'b3dbd888-3ed2-4129-a6a9-7ad4c3d866d7': 'control', // SIMILAR_VODS
        'b29d055f-74f2-40b9-9383-9c4b79b30360': 'control', //CDN_EXPERIMENT
        'dd2d60cd-b76b-4beb-a38c-ea60df88b3cc': 'no', // CREATIVE_UNLIKELY_HERO
        '36a0e500-f117-41dd-8421-3e3db7d567dd': 'communities', // CREATIVE_DIRECTORY_CVS
        'f60b889e-0327-46a8-ad7b-0d402717da45': 'no', // CREATIVE_SIDEBAR_NAVIGATION
        'b86f6c73-d333-4d80-ab45-07cfff39aede': 'control', // CSGO_LANGUAGE_SAMPLE
        '171906a2-6e34-4d0e-879c-a76a19f19097': 'related_first', // VOD_PAGE_RECOMMENDATION_ORDER
        '355ff3e2-38b5-449a-8ab8-a52b5d3ab817': 'control', // REMOVE_CSGO_DIRECTORY
        '653cc0db-d332-4df6-b224-15c5c481f7e7': 'control', // LANGUAGE_DIRECTORY_FILTER
        '8a557906-5bfd-4790-b26c-cda8209567a7': '2', // LANGUAGE_DIRECTORY_ROWCOUNT
        '852b3485-a831-4580-b7bf-acf819977704': 'control', // CHANNEL_VIDEOS_TAB
        '04165981-17be-4593-afbd-762a380f6838': 'false', // MESSAGE_DELETED_EXPERIMENT
        '4f5c0aa5-292d-4ed3-9b2a-f9da6ea195f2': 'no', // RESUME_WATCHING_BANNER
        '98f3f2a5-9e4e-4ba8-aabe-2ff85e7309ee': 'control', // CHAT_RULES_EXPERIMENT
        '6a857f53-de28-4025-8983-3cada70538cd': 'control', // ESL_CSGO_STEAM_LINK
        '3ae835b6-3015-440c-8177-755bdbbbf29e': 'old', // CHANNEL_PAGE_REDESIGN
        '8ace0f50-8afd-424a-a086-3e61b3e66da0': 'off', // MESSAGE_HISTORY
        '2c1c9b8c-530c-4011-a2a0-e93c0e14d8c2': 'off', // BITS_FOR_ADS
        '428d3b07-cc7a-424f-aad0-971f5415879a': 'disabled', // NEXUS_ROLLOUT
        'cc164e1e-1361-4730-8d9b-0091a0f9cb8f': 'no', // DETERMINATION (Persistent Player)
        '5380a8cf-e5cf-497e-9c6c-16cb1c881e0c': 'control', // WATCH_NOW_RIGHTBAR
        'aece7525-dceb-49ba-af1b-242c1ae45831': 'yes', // CHANNEL_LOGIN_CTA
        '3e011e23-ef29-46a5-af4b-a86e15d8c9e6': 'no_show', // DISCOVER_SHOW_COVIEWS
        'af8f152a-f618-416e-8b79-d6ac30479018': 'control', // PERPETUA (Video Collections)
        '264f75af-a787-4a40-8654-40d78b4d8b41': 'no', // EXTENSIONS
        '0670f0ea-3b5c-41a8-946d-114ef4a42540': 'control', // INTL_I18N
        '95869c70-08ce-4e58-a82e-bcaaaf1f8dc2': 'hide', // DISCOVER_HIDE_RECENTLY_WATCHED_STREAMS
        '1b905261-e257-4703-ac84-12a6a9099935': 'control', // CLIENT_BATCH_SPADE
        '42f5eea6-c548-4791-b767-9c7e29b73ef6': 'control', // CLIENT_BATCH_MIXPANEL
        '2858bc04-3f98-4808-a2dd-86555885ca90': 'control', // CLIPS_FEEL_IT_COMING (Clips on Channel Page)
        '9649684c-6d3f-423d-9d3c-f4296efee975': 'control', // CLIPS_HEAR_ME_NOW (Clips on Game Directory Page)
        '05d8869f-e037-4955-b80a-7c361f9ddffb': 'no', // NEWS_FEED_REDESIGN
        '1710cf57-352c-4d09-b2c1-3d40bdf79b30': 'control', // VOD_UPLOAD_UNITS_V3
        '5397de92-0538-42d1-977c-11842e03c9e5': 'no', // ADOPT
        'b2925d54-cebb-4e1d-a50d-9dd2b1ea850e': 'control', // ONSITE_NOTIFICATIONS
        '9b0cc0db-f52c-435f-832d-ba5ac5fc1d57': 'control', // CHOMPY (VOD timed comments)
        'fc494cf9-3a22-448e-b262-ba9e218559e5': 'control',
        'd4d938f7-bdc2-42cd-afd0-f434e4192c29': 'no', // ORC
        '8d2e5bd8-c305-455f-b7ff-ca6fc2ea8710': '2' // LANGUAGE_DIRECTORY_ROWCOUNT_V2
      },
      OVERRIDES_KEY = 'experiment_overrides';

  /* Manual/hardcoded overrides can be added by specifying a mapping between
     experiment UUIDs and an experiment group, i.e.:
      overrides[experiment_uuid] = some_group;
  */
  var overrides = {};
  var staffExperimentOverrides = {
    'BROWSE_EXPERIMENT': 'variant2',
    'CSGO_LANGUAGE_SAMPLE': 'localized',
    'LANGUAGE_DIRECTORY_FILTER': 'full',
    'CLIPS_ENABLED': 'yes',
    'ESL_CSGO_STEAM_LINK': 'show-cta',
    'CHANNEL_PAGE_REDESIGN': 'new',
    'DETERMINATION': 'yes',
    'DISCOVER_SHOW_COVIEWS': 'show',
    'CHOMPY': 'experiment',
    'ONSITE_NOTIFICATIONS': 'variant1',
    'CLIPS_FEEL_IT_COMING': 'variant1',
    'CLIPS_HEAR_ME_NOW': 'variant1',
    'SNAIL': 'early',
    'PERPETUA': 'early'
  };

  _.each(Object.keys(staffExperimentOverrides), function(experiment) {
    overrides[EXPERIMENTS_UUID_MAP[experiment]] = Twitch.user().then(function(user) {
      if (user && user.is_staff) {
        return staffExperimentOverrides[experiment];
      } else {
        return RSVP.Promise.reject();
      }
    }, function(e) {
      if (e && e.status === 401) {
        /* Silence known error: unauthenticated */
        return;
      }
      throw e;
    });
  });

  /* URL and cookie overrides */
  // jscs:disable requireCamelCaseOrUpperCaseIdentifiers
  var urlOverrides = Twitch.url_params().experiments,
  // jscs:enable requireCamelCaseOrUpperCaseIdentifiers
      overridesString = cookie.get(OVERRIDES_KEY),
      cookieOverrides = {};

  try {
    if (overridesString) {
      cookieOverrides = JSON.parse(overridesString);
    }
  } catch (e) {
    console.warn("Failed to parse experiment overrides", e);
  }

  _.extend(overrides, cookieOverrides, urlOverrides);

  var minixperimentConfig = {
    defaults: EXPERIMENT_DEFAULTS,
    deviceID: Twitch.idsForMixpanel.getOrCreateUniqueId(),
    overrides: overrides,
    provider: new Minixperiment.providers.local(EXPERIMENTS_CONFIG),
    Promise: RSVP.Promise,
    platform: 'web',
    login: null
  };

  var minixperimentClient;
  var _configureClient = Twitch.user().then(function (userData) {
    return userData.login;
  }, function () {
    return null;
  }).then(function (login) {
    minixperimentConfig.login = login;
    minixperimentClient = new Minixperiment.Client(minixperimentConfig);
  });

  /* Public API */
  var getExperimentValue = function (experimentName) {
    return _configureClient.then(function () {
      var experimentHash = EXPERIMENTS_UUID_MAP[experimentName];
      return minixperimentClient.get(experimentHash);
    });
  };

  var overrideExperimentValue = function (experimentName, group) {
    if (!experimentName || !group) {
      return;
    }

    var newOverrides = {},
        currentOverrides = cookie.get(OVERRIDES_KEY),
        experimentUuid = EXPERIMENTS_UUID_MAP[experimentName];

    try {
      if (currentOverrides) {
        newOverrides = JSON.parse(currentOverrides);
      }
    } catch (e) {
      console.warn("Failed to parse experiment overrides", e);
    }

    if (experimentUuid) {
      newOverrides[experimentUuid] = group;
    }

    cookie.set(OVERRIDES_KEY, JSON.stringify(newOverrides));
    console.warn("Experiment overrides require a page refresh to take effect.");
  };

  var clearOverrides = function () {
    cookie.remove(OVERRIDES_KEY);
    console.warn("Clearing experiment overrides require a page refresh to take effect.");
  };

  var experiments = {
    getExperimentValue: getExperimentValue,
    overrideExperimentValue: overrideExperimentValue,
    clearOverrides: clearOverrides
  };

  Twitch.mixin({
    experiments: experiments
  });
})(Twitch, jQuery);
