/* globals Twitch */

import moduleForComponent from 'web-client/tests/helpers/module-for-component';
import { skip, test } from 'ember-qunit';
import Service from 'ember-service';
import hbs from 'htmlbars-inline-precompile';
import EmberObject from 'ember-object';
import FakePlayer from 'web-client/tests/helpers/fake-player';
import { AuthenticatedSession } from 'web-client/tests/helpers/mock-session-service';
import MockAutohostService from 'web-client/tests/helpers/mock-autohost-service';
import RSVP from 'rsvp';
import { DEFAULT_DASHBOARD_CONFIG } from 'web-client/components/dashboards/live/live-container/component';
import ChatController from 'web-client/controllers/chat';

moduleForComponent('dashboards/live/live-container', 'Integration | Component | dashboards/live/live-container', {
  beforeEach() {
    this.server.create('channel-ember-data', {
      name: 'fooman',
      display_name: 'FooMan'
    });

    this.server.create('channel-ember-data', {
      name: 'twitch',
      display_name: 'Twitch'
    });

    Twitch.video.Player = FakePlayer;

    let ingestServiceStub = Service.extend({
      getHealth() {
        return RSVP.resolve({
          health_code: 100,
          health_reason_codes: [1000]
        });
      },

      getBitrate() {
        return RSVP.resolve({});
      }
    });

    this.register('service:ingest', ingestServiceStub);
    this.register('service:session', AuthenticatedSession);
    this.register('service:autohost', MockAutohostService);
    this.register('controller:chat', ChatController.extend({
      // Clobber this because the default implementation makes an ajax requests
      // The problematic widget is dashboard/live/chat-module
      setCurrentChannelRoom() {}
    }));
  },

  afterEach() {
    Twitch.video.Player = undefined;
  }
});

test('live dashboard retrieves layout config and renders it properly', function(assert) {
  assert.expect(1);

  let storedDashboardConfig = [
    [
      { path: 'dashboards/live/channel-feed', isCollapsed: true },
      { path: 'dashboards/live/video-preview', isCollapsed: true },
      { path: 'dashboards/live/stream-stats', isCollapsed: true },
      { path: 'dashboards/live/host-mode', isCollapsed: true }
    ],
    [
      { path: 'dashboards/live/announcement-module', isCollapsed: true },
      { path: 'dashboards/live/edit-broadcast', isCollapsed: true },
      { path: 'dashboards/live/stream-health', isCollapsed: true },
      { path: 'dashboards/live/run-commercial', isCollapsed: true },
      { path: 'dashboards/live/stream-delay', isCollapsed: true }
    ],
    [
      { path: 'dashboards/live/chat-module', isCollapsed: true }
    ]
  ];

  let expectedDashboardConfig = [
    ['js-dashboard-channel-feed', 'js-dashboard-video-preview', 'js-dashboard-stream-stats', 'js-dashboard-host-mode'],
    ['js-dashboard-announcement-module', 'js-dashboard-edit-broadcast', 'js-dashboard-stream-health', 'js-dashboard-run-commercial', 'js-dashboard-stream-delay'],
    ['js-dashboard-chat-module']
  ];

  let storageServiceStub = Service.extend({
    dashboardConfiguration: JSON.stringify(storedDashboardConfig)
  });

  let channel = EmberObject.create({
    id: 'twitch',
    partner: true,
    delayControlsEnabled: true,
    _id: '00000000',
    followersTotal: 1000,
    views: 10000,
    stream: {
      isOffline: false,
      viewers: 100,
      createdAt: 0,
      _id: 12345678,

      then() {
        return {
          isOffline: false,
          viewers: 100,
          createdAt: 0,
          _id: 12345678
        };
      },

      reload() {
        return RSVP.resolve({
          isOffline: false,
          viewers: 100,
          createdAt: 0,
          _id: 12345678
        });
      }
    }
  });

  this.register('service:storage', storageServiceStub);
  this.set('channel', channel);

  this.render(hbs`{{dashboards/live/live-container channel=channel}}`);
  let dashboardConfig = [];
  this.$('.js-dashboard-column').each((index, column) => {
    let newColumn = [];

    this.$(column).find('[class*=\'js-dashboard\']').each((compIndex, component) => {
      let componentClasses = this.$(component).attr('class').split(' ');

      componentClasses.forEach(componentClass => {
        if (componentClass.indexOf('js-dashboard') >= 0) {
          newColumn.push(componentClass);
        }
      });
    });

    dashboardConfig.push(newColumn);
  });

  assert.deepEqual(dashboardConfig, expectedDashboardConfig, 'retrieved dashboard config is rendered');
});

// pestanoc: error'ing intermittently - Assertion after the final `assert.async` was resolved
skip('live dashboard retrieves layout config and inserts any missing modules', function(assert) {
  assert.expect(1);

  let storedDashboardConfig = [
    [
      { path: 'dashboards/live/video-preview', isCollapsed: true },
      { path: 'dashboards/live/stream-stats', isCollapsed: true },
      { path: 'dashboards/live/host-mode', isCollapsed: true }
    ],
    [
      { path: 'dashboards/live/edit-broadcast', isCollapsed: true },
      { path: 'dashboards/live/stream-health', isCollapsed: true }
    ],
    [
      { path: 'dashboards/live/chat-module', isCollapsed: true }
    ]
  ];

  let expectedDashboardConfig = [
    ['js-dashboard-announcement-module', 'js-dashboard-video-preview', 'js-dashboard-stream-stats', 'js-dashboard-host-mode', 'js-dashboard-stream-delay', 'js-dashboard-run-commercial'],
    ['js-dashboard-channel-feed', 'js-dashboard-edit-broadcast', 'js-dashboard-stream-health'],
    ['js-dashboard-chat-module']
  ];

  let storageServiceStub = Service.extend({
    dashboardConfiguration: JSON.stringify(storedDashboardConfig)
  });

  let channel = EmberObject.create({
    id: 'twitch',
    partner: true,
    delayControlsEnabled: true,
    _id: '00000000',
    followersTotal: 1000,
    views: 10000,
    stream: {
      isOffline: false,
      viewers: 100,
      createdAt: 0,
      _id: 12345678,

      then() {
        return {
          isOffline: false,
          viewers: 100,
          createdAt: 0,
          _id: 12345678
        };
      },

      reload() {
        return RSVP.resolve({
          isOffline: false,
          viewers: 100,
          createdAt: 0,
          _id: 12345678
        });
      }
    }
  });

  this.register('service:storage', storageServiceStub);
  this.set('channel', channel);

  this.render(hbs`{{dashboards/live/live-container channel=channel}}`);
  let dashboardConfig = [];
  this.$('.js-dashboard-column').each((index, column) => {
    let newColumn = [];

    this.$(column).find('[class*=\'js-dashboard\']').each((compIndex, component) => {
      let componentClasses = this.$(component).attr('class').split(' ');

      componentClasses.forEach(componentClass => {
        if (componentClass.indexOf('js-dashboard') >= 0) {
          newColumn.push(componentClass);
        }
      });
    });

    dashboardConfig.push(newColumn);
  });

  assert.deepEqual(dashboardConfig, expectedDashboardConfig, 'missing modules are inserted');
});

test('live dashboard omits modules that the user does not have approval for', function(assert) {
  assert.expect(1);

  let storedDashboardConfig = [
    [
      { path: 'dashboards/live/channel-feed', isCollapsed: true },
      { path: 'dashboards/live/video-preview', isCollapsed: true },
      { path: 'dashboards/live/stream-stats', isCollapsed: true },
      { path: 'dashboards/live/host-mode', isCollapsed: true }
    ],
    [
      { path: 'dashboards/live/announcement-module', isCollapsed: true },
      { path: 'dashboards/live/edit-broadcast', isCollapsed: true },
      { path: 'dashboards/live/stream-health', isCollapsed: true },
      { path: 'dashboards/live/run-commercial', isCollapsed: true },
      { path: 'dashboards/live/stream-delay', isCollapsed: true }
    ],
    [
      { path: 'dashboards/live/chat-module', isCollapsed: true }
    ]
  ];

  let expectedDashboardConfig = [
    ['js-dashboard-video-preview', 'js-dashboard-stream-stats', 'js-dashboard-host-mode'],
    ['js-dashboard-announcement-module', 'js-dashboard-edit-broadcast', 'js-dashboard-stream-health'],
    ['js-dashboard-chat-module']
  ];

  let storageServiceStub = Service.extend({
    dashboardConfiguration: JSON.stringify(storedDashboardConfig)
  });

  let channel = EmberObject.create({
    id: 'fooman',
    partner: false,
    delayControlsEnabled: false,
    _id: '00000000',
    followersTotal: 1000,
    views: 10000,
    stream: {
      isOffline: false,
      viewers: 100,
      createdAt: 0,
      _id: 12345678,

      then() {
        return {
          isOffline: false,
          viewers: 100,
          createdAt: 0,
          _id: 12345678
        };
      },

      reload() {
        return RSVP.resolve({
          isOffline: false,
          viewers: 100,
          createdAt: 0,
          _id: 12345678
        });
      }
    }
  });

  this.register('service:storage', storageServiceStub);
  this.set('channel', channel);

  this.render(hbs`{{dashboards/live/live-container channel=channel}}`);
  let dashboardConfig = [];
  this.$('.js-dashboard-column').each((index, column) => {
    let newColumn = [];

    this.$(column).find('[class*=\'js-dashboard\']').each((compIndex, component) => {
      let componentClasses = this.$(component).attr('class').split(' ');

      componentClasses.forEach(componentClass => {
        if (componentClass.indexOf('js-dashboard') >= 0) {
          newColumn.push(componentClass);
        }
      });
    });

    dashboardConfig.push(newColumn);
  });

  assert.deepEqual(dashboardConfig, expectedDashboardConfig, 'dashboard config is rendered, respective modules omitted');
});

// bchan: unable to trace error: Uncaught TypeError: Cannot read property 'actions' of undefined
skip('defaults to the pre-defined configuration when no config is found from storage', function(assert) {
  assert.expect(1);

  let storageServiceStub = Service.extend({
    dashboardConfiguration: undefined
  });

  this.server.create('bits-recipient-eligibilities', {
    channelId: 0
  });

  let channel = EmberObject.create({
    id: 'twitch',
    partner: true,
    delayControlsEnabled: true,
    _id: '00000000',
    followersTotal: 1000,
    views: 10000,
    stream: {
      isOffline: false,
      viewers: 100,
      createdAt: 0,
      _id: 12345678,

      then() {
        return {
          isOffline: false,
          viewers: 100,
          createdAt: 0,
          _id: 12345678
        };
      },

      reload() {
        return RSVP.resolve({
          isOffline: false,
          viewers: 100,
          createdAt: 0,
          _id: 12345678
        });
      }
    }
  });

  this.register('service:storage', storageServiceStub);
  this.set('channel', channel);

  this.render(hbs`{{dashboards/live/live-container channel=channel}}`);

  let dashboardConfig = [];
  this.$('.js-dashboard-column').each((index, column) => {
    let newColumn = [];

    this.$(column).find('[class*=\'js-dashboard\']').each((compIndex, component) => {
      let componentClasses = this.$(component).attr('class').split(' ');

      componentClasses.forEach(componentClass => {
        if (componentClass.indexOf('js-dashboard') >= 0) {
          newColumn.push(componentClass);
        }
      });
    });

    dashboardConfig.push(newColumn);
  });

  assert.deepEqual(dashboardConfig, DEFAULT_DASHBOARD_CONFIG, 'default dashboard config is rendered');
});
