import Component from 'ember-component';
import computed from 'ember-computed';
import { htmlSafe } from 'ember-string';
import run from 'ember-runloop';

export const SIZES = {
  D: 'default',
  S: 'small',
  XS: 'extraSmall'
};

export default Component.extend({
  layoutName: 'components/progress-bar',
  classNames: ['js-progress-bar-countdown', 'progress-bar', 'progress-bar--countdown'],
  classNameBindings: ['isSmall:progress-bar--sm', 'isExtraSmall:progress-bar--xs'],

  size: SIZES.D,
  duration: 0,
  totalDuration: 0,

  isSmall: computed('size', function () {
    return this.get('size') === SIZES.S;
  }),

  isExtraSmall: computed('size', function () {
    return this.get('size') === SIZES.XS;
  }),

  style: computed('duration', 'totalDuration', function () {
    let duration = this.get('duration');
    let totalDuration = this.get('totalDuration');
    let width = 100;
    if (totalDuration > duration) {
        width = 100 * duration / totalDuration;
    }

    return htmlSafe(`animation-duration:${duration}s; width:${width}%`);
  }),

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

    let duration = this.get('duration') * 1000;
    let completedAction = this.get('completedAction');

    if (duration > 0) {
      run.later(() => {
        (completedAction)();
      }, duration);
    }
  }
});
