import Ember from 'ember';
import layout from '../templates/components/validation-wrapper';
import ValidationBase from '../mixins/validation-base';

const {
  computed,
  Component,
  observer,
  on
  } = Ember;

export default Component.extend(ValidationBase, {
  layout: layout,

  value: null,
  _isWrapperComponent: true,

  _isInitialized: false,
  _setValueInitialization: on('didInsertElement', function() {
    this.set('_isInitialized', true);
  }),
  _runValidations: observer('value', function() {
    if (this.get('_isInitialized')) {
      this.send('validate');
    }
  }),

  valid: false,
  errors: null,

  validationState: computed('valid', function() {
    const valid = this.get('valid');
    let state = {};

    state.isValid = valid === true;
    state.isInvalid = valid === false;
    state.isInitial = valid === null;
    state.text = valid === true ? 'valid' : (valid === false ? 'invalid' : 'initial');

    return state;
  }),

  setState: function(params) {
    this.setProperties({
      errors: params.errors,
      valid: params.valid
    });
  },

  actions: {
    checkForValid() {
      const errors = runValidations(this);

      if (!errors.length) {
        this.setState({
          valid: true,
          errors: null
        });
      }
    },

    validate() {
      const errors = runValidations(this);

      if (errors.length) {
        this.setState({
          valid: false,
          errors: errors
        });
      } else {
        this.setState({
          valid: true,
          errors: null
        });
      }
    },

    reset() {
      this.setState({
        valid: null,
        errors: null
      });
    }
  },

});

@@ -1666,11 +1666,306 @@
 %0A  %7D
-,
 %0A%0A%7D);
+%0A%0A%0Afunction runValidations(self) %7B%0A  const value = self.get('value');%0A  let errors = Ember.A();%0A%0A  if (!self.get('isRequired') && !value) %7B //change to %7C%7C and remove !%0A    return %5B%5D;%0A  %7D%0A%0A  const rules = self.get('selectedRules');%0A%0A  rules.forEach(rule =%3E rule(value, errors));%0A  return errors;%0A%7D
 %0A

add runValidations to wrapper, needs refactored to util