import Controller from 'ember-controller';
import computed from 'ember-computed';
import { assign } from 'ember-platform';

import {
  BADGES_DEFAULT_SUBSCRIBER_18X18_URL,
  BADGES_DEFAULT_SUBSCRIBER_36X36_URL,
  BADGES_DEFAULT_SUBSCRIBER_72X72_URL
} from 'web-client/utilities/urls/static-cdn';

export const POSSIBLE_BADGES = [
  {
    name: 'Base',
    required_tenure_months: 0,
    image_1x_url: BADGES_DEFAULT_SUBSCRIBER_18X18_URL,
    image_2x_url: BADGES_DEFAULT_SUBSCRIBER_36X36_URL,
    image_4x_url: BADGES_DEFAULT_SUBSCRIBER_72X72_URL,
    title: 'Subscriber'
  },
  {
    name: '3-Month',
    required_tenure_months: 3
  },
  {
    name: '6-Month',
    required_tenure_months: 6
  },
  {
    name: '1-Year',
    required_tenure_months: 12
  },
  {
    name: '2-Year',
    required_tenure_months: 24
  }
];

export default Controller.extend({
  // Passed-in property:
  channelID: null,
  isTimedOut: false,

  // Own properties:
  email: 'partnerhelp@twitch.tv',

  badgeList: computed('model.[]', function () {
    let existingBadgeMap = {};

    this.get('model').forEach(badge => {
      existingBadgeMap[badge.required_tenure_months] = badge;
    });

    return POSSIBLE_BADGES.map(possibleBadge => {
      let existingBadge = existingBadgeMap[possibleBadge.required_tenure_months];
      let possibleBadgeClone = assign({}, possibleBadge);

      return assign(possibleBadgeClone, existingBadge);
    });
  }),

  selectedBadge: computed('badgeList.[]', 'selectedIndex', function () {
    let badgeList = this.get('badgeList');
    let selectedIndex = this.get('selectedIndex');

    return badgeList.objectAt(selectedIndex);
  }),

  selectedIndex: 0,

  actions: {
    onBadgeCreate(createdBadge) {
      this.get('model').addObject(createdBadge);
    },

    onBadgeDelete(deletedBadge) {
      let subBadges = this.get('model');
      let badgeToRemoveIndex;

      for (let i = 0; i < subBadges.length; i++) {
        if (subBadges[i].id !== deletedBadge.id) { continue; }

        badgeToRemoveIndex = i;
        break;
      }

      subBadges.removeAt(badgeToRemoveIndex);
    }
  }
});
