import get from 'ember-metal/get';
import Service from 'ember-service';
import computed from 'ember-computed';
import { assign } from 'ember-platform';
import { copy } from 'ember-metal/utils';
import injectService from 'ember-service/inject';
import SettingsModel from 'web-client/models/settings';
import {
  CHEER_PREFIX
} from 'web-client/utilities/bits/constants-config';

const DEFAULT_SCALE = 1;
const DEFAULT_TEMPLATE_OPTIONS = {
  state: 'animated',
  background: 'light',
  scale: DEFAULT_SCALE
};

export default Service.extend({
  bits: injectService(),
  layout: injectService(),

  isLoaded: false,
  config: null,
  regexes: null,

  useDarkTrim: computed.or('layout.isTheatreMode', 'settings.darkMode'),

  settings: computed(function() {
    return SettingsModel.findOne();
  }),

  /* RGB needed for gradients in bits-amount.hbs */
  hexToRgb(hexString = '') {
    let r, g, b;

    hexString = hexString[0] === '#' ? hexString.slice(1) : hexString;
    if (hexString.length < 6) {
      return '';
    }

    r = parseInt(hexString.slice(0, 2), 16);
    g = parseInt(hexString.slice(2, 4), 16);
    b = parseInt(hexString.slice(4, 6), 16);

    return [r, g, b].join(', ');
  },

  /*
   Returns {url, srcSet, color} for the Bits tier for the given amount.
   Defaults to providing gifs for light backgrounds.
   */
  getRenderProperties(bitsAmount, scale = 1, forceDarkMode, isAnimated = true, prefix = CHEER_PREFIX) {
    let config = this._getConfigPrefix(prefix);
    let tierCount = get(config, 'tiers.length') || 0;
    let bitsTier;

    if (tierCount === 0) {
      return {};
    }

    // default to lowest tier
    if (bitsAmount <= 0) {
      bitsTier = config.tiers[0];
    } else {
      for (let i = 0; i < tierCount; i++) {
        let nextTier = config.tiers[i];
        if (bitsAmount >= nextTier.min_bits) {
          bitsTier = nextTier;
        } else {
          break;
        }
      }
    }

    let isDarkMode = this.get('useDarkTrim') || forceDarkMode;
    let templateOptions = {
      background: isDarkMode ? 'dark' : 'light',
      scale: scale,
      state: isAnimated ? 'animated' : 'static'
    };

    let {src, srcSet} = this._constructImageSrc(config.scales, bitsTier, templateOptions);
    return {
      src,
      srcSet,
      tierId: bitsTier.id,
      colorRgb: this.hexToRgb(bitsTier.color),
      colorHex: bitsTier.color
    };
  },

  loadRenderConfig(channelName) {
    if (this.get('isLoaded')) { return; }

    this.get('bits').getEmoteConfig(channelName).then((emoteConfigPayload) => {
      this.set('config', this._transformEmoteConfig(emoteConfigPayload));
      this.set('isLoaded', true);
    });
  },

  _constructImageSrc(scales, bitsTier, options = {}) {
    let defaults = copy(DEFAULT_TEMPLATE_OPTIONS, true);
    let {scale: defaultScale, state, background} = assign(defaults, options);
    let srcSet = '';

    // Not generating srcSet for scales > 1
    if (defaultScale === DEFAULT_SCALE) {
      srcSet = scales.map((scale) => {
        let srcSetUrl = bitsTier.images[background][state][scale];
        return `${srcSetUrl} ${scale}x`;
      }).join(', ');
    }

    return {
      src: bitsTier.images[background][state][defaultScale],
      srcSet
    };
  },

  _getConfigPrefix(prefix) {
    let sanitizedPrefix = prefix.toLowerCase();
    if (!this.get(`config.${sanitizedPrefix}`)) {
      sanitizedPrefix = CHEER_PREFIX;
    }

    return this.get(`config.${sanitizedPrefix}`);
  },

  _transformEmoteConfig(payload){
    let config = {
      prefixes: []
    };

    payload.actions.forEach((action) => {
      config.prefixes.push(action.prefix);
      config[action.prefix.toLowerCase()] = action;
    });

    let regexes = config.prefixes.map((prefix) => {
      return {
        prefix: prefix,
        zeroValue: new RegExp(`^\\s*${prefix}0+\\s*$`, 'i'),
        valid: new RegExp(`^\\s*${prefix}\\d+\\s*$`, 'i')
      };
    });

    this.set('regexes', regexes);

    //Put here instead of in payday because we don't want 3rd parties to know where to get the yellow bit yet
    if (config['cheer'].tiers.length === 5) {
      config['cheer'].tiers.push({
        min_bits: 100000,
        id: "100000",
        color: "#f3a71a",
        images: {
          light: {
            static: {
                1: "https://d3aqoihi2n8ty8.cloudfront.net/actions/cheer/light/static/100000/1.png",
                1.5: "https://d3aqoihi2n8ty8.cloudfront.net/actions/cheer/light/static/100000/1.5.png",
                2: "https://d3aqoihi2n8ty8.cloudfront.net/actions/cheer/light/static/100000/2.png",
                3: "https://d3aqoihi2n8ty8.cloudfront.net/actions/cheer/light/static/100000/3.png",
                4: "https://d3aqoihi2n8ty8.cloudfront.net/actions/cheer/light/static/100000/4.png"
            },
            animated: {
                1: "https://d3aqoihi2n8ty8.cloudfront.net/actions/cheer/light/animated/100000/1.gif",
                1.5: "https://d3aqoihi2n8ty8.cloudfront.net/actions/cheer/light/animated/100000/1.5.gif",
                2: "https://d3aqoihi2n8ty8.cloudfront.net/actions/cheer/light/animated/100000/2.gif",
                3: "https://d3aqoihi2n8ty8.cloudfront.net/actions/cheer/light/animated/100000/3.gif",
                4: "https://d3aqoihi2n8ty8.cloudfront.net/actions/cheer/light/animated/100000/4.gif"
            }
          },
          dark: {
            static: {
               1: "https://d3aqoihi2n8ty8.cloudfront.net/actions/cheer/dark/static/100000/1.png",
               1.5: "https://d3aqoihi2n8ty8.cloudfront.net/actions/cheer/dark/static/100000/1.5.png",
               2: "https://d3aqoihi2n8ty8.cloudfront.net/actions/cheer/dark/static/100000/2.png",
               3: "https://d3aqoihi2n8ty8.cloudfront.net/actions/cheer/dark/static/100000/3.png",
               4: "https://d3aqoihi2n8ty8.cloudfront.net/actions/cheer/dark/static/100000/4.png"
            },
            animated: {
              1: "https://d3aqoihi2n8ty8.cloudfront.net/actions/cheer/dark/animated/100000/1.gif",
              1.5: "https://d3aqoihi2n8ty8.cloudfront.net/actions/cheer/dark/animated/100000/1.5.gif",
              2: "https://d3aqoihi2n8ty8.cloudfront.net/actions/cheer/dark/animated/100000/2.gif",
              3: "https://d3aqoihi2n8ty8.cloudfront.net/actions/cheer/dark/animated/100000/3.gif",
              4: "https://d3aqoihi2n8ty8.cloudfront.net/actions/cheer/dark/animated/100000/4.gif"
            }
          }
        }
      });
    }

    return config;
  }
});
