import Component from 'ember-component';
import run from 'ember-runloop';
import injectService from 'ember-service/inject';
import computed from 'ember-computed';
import env from 'web-client/config/environment';
import RSVP from 'rsvp';
import moment from 'moment';

const POLL_INTERVAL = env.delay.dashboard.pollInterval;

export default Component.extend({
  classNames: ['js-dashboard-host-mode'],

  tmi: injectService(),
  api: injectService(),
  autohost: injectService(),
  store: injectService(),
  storage: injectService(),

  /* Passed in properties */
  channel: null,
  isCollapsed: null,
  isChannelOwner: false,
  trackDashboardEvent() {},

  /* internal properties */
  room: null,
  hosting: null,

  /* Rendering properties*/

  isShowingAllHosts: false,
  isAutohosting: false,
  isShowingHostedBy: true,
  hostsLoaded: false,

  shouldShowSetupAutohost: computed('storage.dismissedAutohostSetupFromDashboard', 'autohost.settings.enabled', function() {
    if (this.get('autohost.settings.enabled')) {
      return false;
    }

    // If it's not set, show autohost
    let dismissedTime = this.get('storage.dismissedAutohostSetupFromDashboard');

    if (!dismissedTime) {
      return true;
    }

    return moment().isAfter(moment(dismissedTime).add(1, 'week'));
  }),

  unseenChannelsCount: 0,

  init() {
    this._super(...arguments);

    this.set('hostedBy', []);
    this.set('unseenChannels', {});

    this._updateAutoHostedBy();

    this.get('tmi.tmiSession')
      .then(session => {
        if (this.isDestroyed) { return; }

        this.set('room', session.getRoom(this.get('channel.id')));
        this._monitorHosts();
      });
  },

  didUpdateAttrs() {
    this._super(...arguments);

    if (!this.get('isCollapsed')) {
      this._retrieveHostInformation();
      this._updateAutoHostedBy();
    }
  },

  _monitorHosts() {
    this.pollTask(next => {
      if (this.get('isDestroyed') || this.get('isDestroying')) { return; }

      if (!this.get('isCollapsed')) {
        this._retrieveHostInformation();
        this._updateAutoHostedBy();
      }
      this.runTask(next, POLL_INTERVAL);
    }, 'host-mode#monitor-hosts');
  },

  _retrieveHostInformation() {
    this._updateHostTarget()
      .then(() => {
        if (this.isDestroyed) { return; }

        this._updateHosts();
      });
  },

  _updateHosts() {
    // Channel owner can use kraken api
    if (this.get('isChannelOwner')) {
      let api = this.get('api');
      return api.authRequest('get', 'hosters').then((payload) => {
        if (this.isDestroyed) { return; }

        run(() => this._updateHostedBy(payload.hosters));
      });
    }

    return this.get('room')
      .then(room => {
        if (this.isDestroyed) { return; }

        return room.hosts({ useDeprecatedResponseFormat: true });
      })
      .then(({ hosts }) => {
        if (this.isDestroyed) { return; }

        let hosters = hosts.map((h) => ({ host_login: h.host }));
        run(() => this._updateHostedBy(hosters));
      });
  },

  _updateHostedBy(hostedBy) {
    let hostedByUsers = [];

    RSVP.Promise.all(hostedBy.map((hoster) => {
      if (this.isDestroyed) { return; }

      return this.get('store').findRecord('user', hoster.host_login)
        .then(hostUser => {
          if (this.isDestroyed) { return; }

          hostedByUsers.push(hostUser);
        });
    })).then(() => {
      if (this.isDestroyed) { return; }

      this.set('hostedBy', hostedByUsers);
      this.set('hostsLoaded', true);
    });
  },

  _updateHostTarget() {
    return this.get('room')
      .then(room => {
        if (this.isDestroyed) { return; }

        return room.hostTarget({ useDeprecatedResponseFormat: true });
      })
      .then(host => {
        if (this.isDestroyed) { return; }

        if (!host.host_target) {
          run(() => this.set('hosting', null));
          return RSVP.resolve();
        }

        return this.get('store').findRecord('user', host.host_target)
          .then(hostUser => {
            if (this.isDestroyed) { return; }

            run(() => this.set('hosting', hostUser));
          });
      });
  },

  _updateAutoHostedBy() {
    let autohost = this.get('autohost');
    let existingAutoHosters = {};

    this.get('autohost.autoHostedBy').forEach((channel) => {
      existingAutoHosters[channel.get('_id')] = true;
    });

    autohost.updateAutoHostedBy().then(channels => {
      if (this.isDestroyed) { return; }

      if (!this.get('isShowingHostedBy')) { return; }

      let unseenChannels = this.get('unseenChannels');
      channels.forEach((channel) => {
        let channelID = channel.get('_id');

        if (!existingAutoHosters[channelID]) {
          unseenChannels[channelID] = true;
        }
      });

      this.set('unseenChannels', unseenChannels);
      this.set('unseenChannelsCount', Object.keys(unseenChannels).length);
    });
  },

  actions: {
    dismissSetupAutohost() {
      this.set('storage.dismissedAutohostSetupFromDashboard', moment());
    },

    showHostedBy() {
      this.set('isShowingHostedBy', true);
    },

    showAutoHostedBy() {
      this.set('isShowingHostedBy', false);
      this.set('unseenChannels', {});
      this.set('unseenChannelsCount', 0);
    }
  }
});
