import Component from 'ember-component';
import computed from 'ember-computed';
import { assert } from 'ember-metal/utils';

const DEFAULT_CLASS_NAME = 'simple-checkbox';
const AVAILABLE_POSITIONS = Object.freeze(['top', 'middle']);

export default Component.extend({
  classNames: [`${DEFAULT_CLASS_NAME}`],
  classNameBindings: [`disabled:${DEFAULT_CLASS_NAME}--disabled`, 'flexAlignmentClass'],

  autofocus: false,
  checkboxId: null,
  checked: null,
  disabled: false,
  position: 'middle',
  readonly: false,
  update() {},

  checkboxAlignmentClass: computed('position', function() {
    let position = this.get('position');
    return `${DEFAULT_CLASS_NAME}__input--${position}`;
  }),

  flexAlignmentClass: computed('position', function() {
    let position = this.get('position');
    if (position === 'middle') {
      return `flex--verticalCenter`;
    }
  }),

  _update() {
    let checkboxId = this.get('checkboxId');
    let $checkbox = this.$(`#${checkboxId}`);

    assert(`Component must have at least one element with an id='{{elementId}}_$checkbox'`, $checkbox.length);
    $checkbox.prop('checked', Boolean(this.get('checked')));

    if (this.get('disabled') || this.get('readonly')) {
      return;
    }
    $checkbox.focus();
    this.update();
  },

  click() {
    this._update();
  },

  didReceiveAttrs() {
    if (!(this.get('disabled') || this.get('readonly'))) {
      assert(`Attribute 'update' must be a function`, typeof this.update === 'function');
    }

    let position = this.get('position');
    assert(`Unsupported position '${position}'.  Available: ${AVAILABLE_POSITIONS.join(', ')}`,
      AVAILABLE_POSITIONS.indexOf(position) >= 0);
  },

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

    let elementId = this.get('elementId');
    this.set('checkboxId', `${elementId}_checkbox`);
  }
});
