'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var React = require('react');
var PropTypes = require('prop-types');

var _require = require('hadron-react-components'),
    OptionSelector = _require.OptionSelector;

var ValidationActions = require('../actions');
var Editable = require('./common/editable');

var _require2 = require('react-bootstrap'),
    Grid = _require2.Grid,
    Row = _require2.Row,
    Col = _require2.Col,
    FormGroup = _require2.FormGroup,
    FormControl = _require2.FormControl;

// const debug = require('debug')('validation:json-view');

var JSONView = function (_React$Component) {
  _inherits(JSONView, _React$Component);

  function JSONView(props) {
    _classCallCheck(this, JSONView);

    var _this = _possibleConstructorReturn(this, (JSONView.__proto__ || Object.getPrototypeOf(JSONView)).call(this, props));

    _this.state = {
      isValidJSON: true,
      input: props.validatorDoc ? JSON.stringify(props.validatorDoc.validator, null, 2) : '{}'
    };
    return _this;
  }

  _createClass(JSONView, [{
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(newProps) {
      this.setState({
        input: JSON.stringify(newProps.validatorDoc.validator, null, 2)
      });
    }
  }, {
    key: 'onInputChanged',
    value: function onInputChanged(evt) {
      this.setState({
        input: evt.target.value
      });
    }
  }, {
    key: 'onBlur',
    value: function onBlur() {
      var doc = this.validate();
      if (doc) {
        ValidationActions.setValidatorDocument(doc);
      }
    }

    /**
     * New value from the validation action dropdown chosen.
     *
     * @param {String} action    the chosen action, one of `warn`, `error`.
     */

  }, {
    key: 'onActionSelect',
    value: function onActionSelect(action) {
      ValidationActions.setValidationAction(action, false);
    }

    /**
     * New value from the validation level dropdown chosen.
     *
     * @param {String} level    the chosen level, one of `off`, `moderate`, `strict`
     */

  }, {
    key: 'onLevelSelect',
    value: function onLevelSelect(level) {
      ValidationActions.setValidationLevel(level, false);
    }

    /**
     * The "Cancel" button from the `Editable` component has been clicked.
     * Revert all changes to the server state.
     */

  }, {
    key: 'onCancel',
    value: function onCancel() {
      this.setState({
        isValidJSON: true
      });
      ValidationActions.cancelChanges();
    }

    /**
     * The "Update" button from the `Editable component has been clicked.
     * Send the new validator doc to the server.
     */

  }, {
    key: 'onUpdate',
    value: function onUpdate() {
      ValidationActions.saveChanges();
    }
  }, {
    key: 'validate',
    value: function validate() {
      try {
        var doc = {
          validator: JSON.parse(this.state.input),
          validationLevel: this.props.validationLevel,
          validationAction: this.props.validationAction
        };
        this.setState({
          isValidJSON: true
        });
        return doc;
      } catch (e) {
        this.setState({
          isValidJSON: false
        });
        return false;
      }
    }

    /**
     * Render status row component.
     *
     * @returns {React.Component} The component.
     */

  }, {
    key: 'render',
    value: function render() {
      var editableProps = {
        editState: this.props.editState,
        childName: 'Validation',
        onCancel: this.onCancel.bind(this),
        onUpdate: this.onUpdate.bind(this)
      };

      if (!this.state.isValidJSON) {
        editableProps.editState = 'error';
        editableProps.errorMessage = 'Input is not valid JSON.';
        delete editableProps.childName;
      }
      var actionOptions = { warn: 'Warning', error: 'Error' };
      var levelOptions = { off: 'Off', moderate: 'Moderate', strict: 'Strict' };

      return React.createElement(
        Editable,
        editableProps,
        React.createElement(
          Grid,
          { fluid: true, className: 'json-view' },
          React.createElement(
            Row,
            { className: 'header' },
            React.createElement(
              Col,
              { lg: 12, md: 12, sm: 12, xs: 12 },
              React.createElement(
                'div',
                { className: 'pull-right' },
                React.createElement(OptionSelector, {
                  id: 'validation-action-selector',
                  bsSize: 'xs',
                  options: actionOptions,
                  title: actionOptions[this.props.validationAction],
                  label: 'Validation Action',
                  onSelect: this.onActionSelect.bind(this),
                  disabled: !this.props.isWritable
                }),
                React.createElement(OptionSelector, {
                  id: 'validation-level-selector',
                  bsSize: 'xs',
                  options: levelOptions,
                  title: levelOptions[this.props.validationLevel],
                  label: 'Validation Level',
                  onSelect: this.onLevelSelect.bind(this),
                  disabled: !this.props.isWritable
                })
              )
            )
          ),
          React.createElement('hr', null),
          React.createElement(
            Row,
            null,
            React.createElement(
              Col,
              { lg: 12, md: 12, sm: 12, xs: 12 },
              React.createElement(
                FormGroup,
                { validationState: this.state.errorState },
                React.createElement(FormControl, {
                  componentClass: 'textarea',
                  className: 'json-input json-input-textarea',
                  value: this.state.input,
                  onChange: this.onInputChanged.bind(this),
                  onBlur: this.onBlur.bind(this),
                  disabled: !this.props.isWritable
                })
              )
            )
          )
        )
      );
    }
  }]);

  return JSONView;
}(React.Component);

JSONView.propTypes = {
  editState: PropTypes.oneOf(['unmodified', 'modified', 'updating', 'error', 'success']).isRequired,
  validationAction: PropTypes.oneOf(['warn', 'error']).isRequired,
  validationLevel: PropTypes.oneOf(['off', 'moderate', 'strict']).isRequired,
  validatorDoc: PropTypes.object.isRequired,
  isWritable: PropTypes.bool
};

JSONView.defaultProps = {
  isWritable: false
};

JSONView.displayName = 'JSONView';

module.exports = JSONView;