/* globals i18n */

import Component from 'ember-component';
import injectService from 'ember-service/inject';
import computed from 'ember-computed';
import moment from 'moment';
import { htmlSafe } from 'ember-string';
import env from 'web-client/config/environment';

const SECONDS_REMAINING_MESSAGE = i18n('{{seconds}} seconds remaining...');
const LAST_AD_PLAYED_MESSAGE = i18n('{{lastAdPlayed}} since last ad');
const RUN_COMMERCIAL_BUTTON_LABEL = i18n('Run Ad ({{duration}})');

const COMMERCIAL_TIMEOUT = 480000;
const POLL_INTERVAL = env.delay.dashboard.pollInterval;

export default Component.extend({
  ads: injectService(),
  tracking: injectService(),

  classNames: ['js-dashboard-run-commercial'],

  /* passed in properties */
  channel: null,
  isLive: null,
  trackDashboardEvent() {},

  /* internal properties */
  isLoading: true,
  duration: 30,
  prevDuration: 30,
  lastAdPlayed: null,
  lastAdPlayedMoment: null,
  totalAdsPlayed: 0,
  secondsRemaining: 0,
  adPlaying: null,
  timeoutRunCommercial: false,
  adError: false,
  maxBreakLength: 180,

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

    let adsService = this.get('ads');
    let channelId = this.get('channel._id');

    adsService.getAdBreakSettings(channelId).then(response => {
      if (this.isDestroyed) { return; }
      this.set('maxBreakLength', response.max_break_length);
    }).finally(() => {
      if (this.isDestroyed) { return; }
      this.set('isLoading', false);
    });
  },

  // CB-276: Allow channels to play commercials sooner than 8 min timeout.
  // Some users will receive an error if they must wait 8 minutes.
  isRunCommercialDisabled: computed('timeoutRunCommercial', 'isLive', function() {
    return this.get('timeoutRunCommercial') || !this.get('isLive');
  }),

  percentRemaining: computed('secondsRemaining', 'duration', function() {
    // Returns whole % number between 0 and 100
    let secondsRemaining = this.get('secondsRemaining');
    let duration = this.get('duration');
    let percent = Math.floor((secondsRemaining / duration) * 100);
    return htmlSafe(`width: ${ percent }%`);
  }),

  minutesPlayed: computed('totalAdsPlayed', function() {
    let totalAdsPlayed = this.get('totalAdsPlayed');
    let minutesPlayed = moment().startOf('day').seconds(totalAdsPlayed).format('m:ss');

    return htmlSafe(minutesPlayed);
  }),

  secondsRemainingMessage: computed('secondsRemaining', function() {
    let secondsRemaining = this.get('secondsRemaining');
    let message = SECONDS_REMAINING_MESSAGE;
    return htmlSafe(message.replace('{{seconds}}', secondsRemaining));
  }),

  lastAdPlayedMessage: computed('lastAdPlayed', function() {
    let lastAdPlayed = this.get('lastAdPlayed');
    let message = LAST_AD_PLAYED_MESSAGE;
    return htmlSafe(message.replace('{{lastAdPlayed}}', lastAdPlayed));
  }),

  runCommercialButtonLabel: computed('duration', function() {
    let duration = this.get('duration');
    let label = RUN_COMMERCIAL_BUTTON_LABEL;
    let formattedDuration = moment().startOf('day').seconds(duration).format('m:ss');

    return htmlSafe(label.replace('{{duration}}', formattedDuration));
  }),

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

      let lastAdPlayedMoment = this.get('lastAdPlayedMoment');
      let now = moment();
      this.set('lastAdPlayed', lastAdPlayedMoment.fromNow(true));

      // it has been 8 minutes since the last ad, enable run commercial
      if (now.diff(lastAdPlayedMoment) > COMMERCIAL_TIMEOUT) {
        this.set('timeoutRunCommercial', false);
      }

      this.runTask(next, POLL_INTERVAL);
    });
  },

  actions: {
    durationChanged(value) {
      let prevDuration = this.get('duration');
      let trackDashboardEvent = this.get('trackDashboardEvent');

      trackDashboardEvent('live_dashboard_run_ad', {
        action: 'slidermove',
        slider_start_position: prevDuration,
        slider_position: parseInt(value)
      });

      this.set('prevDuration', prevDuration);
      this.set('duration', parseInt(value));
    },

    removeError() {
      this.set('adError', false);
    },

    runCommercial() {
      let duration = parseInt(this.get('duration'));
      let channelId = this.get('channel._id');
      let isUpdateSuccessful = null;
      this.set('adError', false);

      this.get('ads').startCommercial(channelId, duration)
        .then(() => {
          if (this.isDestroyed) { return; }

          let lastAdPlayed = moment();
          let secondsRemaining = duration;
          isUpdateSuccessful = true;

          this.set('lastAdPlayedMoment', lastAdPlayed);
          this.set('totalAdsPlayed', parseInt(this.get('totalAdsPlayed')) + duration);
          this.set('adPlaying', true);
          this.set('timeoutRunCommercial', true);

          this._updateLastAdPlayed();
          this.runTask(() => this.set('adPlaying', false), duration * 1000);

          this.pollTask(next => {
            if (this.isDestroyed) { return; }

            this.set('secondsRemaining', secondsRemaining--);
            if (secondsRemaining > 0) {
              this.runTask(next, 1000);
            }
          });

          this.get('tracking').trackEvent({
            event: 'commercial_request',
            data: {
              channel: this.get('channel.id'),
              trigger: 'ember',
              length: duration
            }
          });
        }, () => {
          if (this.isDestroyed) { return; }

          isUpdateSuccessful = false;
          this.set('adError', true);
        })
        .finally(() => {
          if (this.isDestroyed) { return; }

          let trackDashboardEvent = this.get('trackDashboardEvent');

          trackDashboardEvent('live_dashboard_run_ad', {
            action: 'runadclick',
            slider_start_position: this.get('prevDuration'),
            slider_position: duration,
            update_successful: isUpdateSuccessful
          });
        });
    }
  }
});
