import expect from 'expect';
import fetchMock from 'fetch-mock';

import {
  mockAllBadges,
  GLOBAL_SUBSCRIBER_VERSION_0_URL,
  TEST_CHANNEL_ID,
} from 'mtest/chat/helpers/badgerFetchMocks';

import { BadgerService } from 'mweb/chat/badgerService';

describe('badger', () => {
  let badger: BadgerService;

  beforeEach(() => {
    badger = new BadgerService();
  });

  describe('bare singleton', () => {
    it('constructs without badges', () => {
      expect(badger.badges).toNotExist();
    });
  });

  describe('with fetches', () => {
    beforeEach(() => {
      mockAllBadges();
    });

    afterEach(() => {
      expect(fetchMock.done()).toEqual(true);
      fetchMock.restore();
    });

    /* tslint:disable:no-string-literal */
    it('fetches badges on init and merges subscriber badges with channel specifics', () => {
      return badger.init(TEST_CHANNEL_ID).then(() => {
        expect(badger.badges).toExist();
        // ensure general badges are available
        expect(badger.badges['warcraft']).toExist();
        // ensure general badges are still available as well
        expect(badger.badges['subscriber'].versions['1']).toExist();
        // ensure channel-specific subscriber badges have overwritten general badges
        expect(
          badger.badges['subscriber'].versions['0'].image_url_1x,
        ).toNotEqual(GLOBAL_SUBSCRIBER_VERSION_0_URL);
      });
    });
    /* tslint:enable:no-string-literal */

    it('returns proper badge info from getBadgeData', () => {
      return badger.init(TEST_CHANNEL_ID).then(() => {
        const badgeData = badger.getBadgeData({
          subscriber: '12',
          warcraft: 'horde',
        });
        expect(badgeData.length).toEqual(2);
        expect(badgeData[0].alt).toEqual('1-Year Subscriber');
        expect(badgeData[1].alt).toEqual('For the Horde!');
      });
    });

    it('safely ignores and filters unknown badges', () => {
      return badger.init(TEST_CHANNEL_ID).then(() => {
        const badgeData = badger.getBadgeData({
          subscriber: '12',
          starcraft: 'zerg',
        });
        expect(badgeData.length).toEqual(1);
        expect(badgeData[0].alt).toEqual('1-Year Subscriber');
      });
    });

    it('returns empty list from getBadgeData when there are no badges', () => {
      return badger.init(TEST_CHANNEL_ID).then(() => {
        expect(badger.getBadgeData(null).length).toEqual(0);
      });
    });
  });
});
