import Component from 'ember-component';
import run from 'ember-runloop';

export default Component.extend({
  fallingBits: null,
  classNameBindings: ['isLeft:bits-tag__left-player'],
  playerTotalAfterAnim: 0,
  displayedTotal: 0,
  formattedDisplayedTotal: 0,

  init(){
    this._super(...arguments);
    this.set('fallingBits', []);
  },

  didReceiveAttrs(){
    if (this.get('playerTotal') === 0) {
      this.set('displayedTotal', 0);
      this.set('playerTotalAfterAnim', 0);
      this._bitFinishesDropping({ value: 0 });
      return;
    }

    let newBit = {
      value: this.get('playerTotal') - this.get('playerTotalAfterAnim')
    };

    if (newBit.value > 0) {
      this.get('fallingBits').addObject(newBit);
      this.set('playerTotalAfterAnim', this.get('playerTotal'));
      run.later(() => {
        this._bitFinishesDropping(newBit);
      }, 425);
    }
  },

  _bitFinishesDropping: function(newBit){
    this.get('fallingBits').removeObject(newBit);
    this.set('displayedTotal', parseInt(this.get('displayedTotal') + parseInt(newBit.value)));
    this.set('formattedDisplayedTotal', this._formatTotal(this.get('displayedTotal')));
  },

  _formatTotal: function(total) {
    if (total < 10000) {
      return total.toLocaleString();
    }

    let formatTotal = (total/1000).toFixed(1).toLocaleString();
    return `${formatTotal}K`;
  }

});
