import Component from 'ember-component';
import injectService from 'ember-service/inject';
import run from 'ember-runloop';
import computed from 'ember-computed';
import { htmlSafe } from 'ember-string';
import { storageFor } from 'ember-local-storage';
import ENV from 'web-client/config/environment';

const SHOW_DURATION = 5 * 60 * 1000;
const DISMISS_DURATION = 10 * 1000;

export default Component.extend({
  store: injectService(),
  experiments: injectService(),
  tracking: injectService(),
  session: injectService(),
  storage: storageFor('follow-cta'),

  /* public */
  channel: null,

  /* private */
  isHidden: true,
  dismissDurationSecs: Math.round(DISMISS_DURATION / 1000),

  progressBarStyle: computed('dismissDurationSecs', function () {
    return htmlSafe(`animation-duration: ${ this.get('dismissDurationSecs') }s;`);
  }),

  init() {
    this._super(...arguments);
    this._showTimer = null;
    this._hideTimer = null;
    this._experimentVariant = null;

    let channel = this.get('channel.name').toLowerCase();
    if (this.get(`storage.dismisses.${channel}`)) {
      // if the user has already dismissed this notification, don't show it again
      return;
    }

    this.get('store').findRecord('follow', channel).then((follow) => {
      if (this.isDestroyed) { return; }

      let isFollowing = follow && follow.get('isFollowing');
      // During acceptance tests -- waiting 5 minutes can cause tests to timeout.
      // Only start the timer if we're not running tests.
      if (ENV.environment !== 'test' && !isFollowing) {
        let waitDuration = SHOW_DURATION;
        if (localStorage.getItem('follow-cta-debug') === 'true') {
          waitDuration = 10 * 1000;
        }
        this._showTimer = this.runTask('_show', waitDuration);
      }
    });
  },

  willDestroyElement() {
    this._super(...arguments);
    this._clearTimers();
  },

  _clearTimers() {
    run.cancel(this._showTimer);
    run.cancel(this._hideTimer);
  },

  _show() {
    if (!this.get('channel.hostModeTarget')) {
      this.set('isHidden', false);
      this._hideTimer = this.runTask('_hide', DISMISS_DURATION);
      this._trackShow();
    }
  },

  _hide() {
    this.set('isHidden', true);
    this._clearTimers();
  },

  _trackShow() {
    let data = {
      channel: this.get('channel.id')
    };
    let { isAuthenticated, userData } = this.get('session');
    if (isAuthenticated) {
      data.login = userData.login;
    }
    this.get('tracking').trackEvent({
      event: 'follow_cta_show',
      data
    });
  },

  actions: {
    addFollowTrackingData: function() {
      return {
        cta_visible: !this.get('isHidden')
      };
    },

    onFollowClick: function() {
      this._hide();
    },

    dismiss: function() {
      let channel = this.get('channel.name').toLowerCase();
      let dismisses = this.get('storage.dismisses');
      dismisses[channel] = true;
      this.set('storage.dismisses', dismisses);
      this._hide();
    }
  }

});
