'use strict';

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

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,
    Tooltip = _require.Tooltip;

var ValidationActions = require('../actions');
var Rule = require('./rule');
var Editable = require('./common/editable');
var _ = require('lodash');

var ReactBootstrap = require('react-bootstrap');
var Grid = ReactBootstrap.Grid;
var Row = ReactBootstrap.Row;
var Col = ReactBootstrap.Col;
var Button = ReactBootstrap.Button;
var Table = ReactBootstrap.Table;

// const debug = require('debug')('validation:rule-builder');

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

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

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

    _this.state = {
      isValid: true,
      forceRenderKey: 0
    };
    return _this;
  }

  _createClass(RuleBuilder, [{
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(props) {
      this.validate(false);
      if (props.editState === 'unmodified' && this.props.editState !== 'unmodified') {
        // force a complete redraw of the component by increasing the key
        this.setState({
          forceRenderKey: this.state.forceRenderKey + 1,
          isValid: true
        });
      }
    }

    /**
     * Add button clicked to create a new rule.
     */

  }, {
    key: 'onAddClick',
    value: function onAddClick() {
      ValidationActions.addValidationRule();
    }

    /**
     * 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, true);
    }

    /**
     * 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, true);
    }

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

  }, {
    key: 'onCancel',
    value: function onCancel() {
      ValidationActions.cancelChanges();
    }

    /**
     * The "Update" button from the `Editable component has been clicked.
     * Check that all rules are valid, then send the new validator doc to
     * the server.
     */

  }, {
    key: 'onUpdate',
    value: function onUpdate() {
      if (this.validate(true)) {
        ValidationActions.saveChanges();
      }
    }
  }, {
    key: 'validate',
    value: function validate(force) {
      var _this2 = this;

      var isValid = _.every(this.props.validationRules, function (rule) {
        return _this2.refs[rule.id].validate(force);
      });
      this.setState({
        isValid: isValid
      });
      return isValid;
    }
  }, {
    key: 'renderRules',
    value: function renderRules() {
      var _this3 = this;

      return _.map(this.props.validationRules, function (rule) {
        return React.createElement(Rule, _extends({ ref: rule.id,
          key: rule.id,
          isWritable: _this3.props.isWritable,
          serverVersion: _this3.props.serverVersion
        }, rule));
      });
    }
  }, {
    key: 'renderAddButton',
    value: function renderAddButton() {
      return React.createElement(
        Button,
        {
          bsStyle: 'primary',
          bsSize: 'xsmall',
          disabled: !this.props.isWritable,
          onClick: this.onAddClick.bind(this) },
        '+ Add Rule'
      );
    }

    /**
     * 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),
        key: this.state.forceRenderKey
      };

      if (!this.state.isValid) {
        editableProps.editState = 'error';
        editableProps.errorMessage = 'Input is not valid.';
        delete editableProps.childName;
      }

      var tooltipId = 'validation-rule-is-not-writable';
      var isNotWritableTooltip = this.props.isWritable ? null : React.createElement(Tooltip, { id: tooltipId });
      var tooltipText = 'This action is not available on a secondary node';
      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: 'rule-builder' },
          React.createElement(
            Row,
            { className: 'header' },
            React.createElement(
              Col,
              { lg: 6, md: 6, sm: 6, xs: 6 },
              React.createElement(
                'div',
                { className: 'tooltip-button-wrapper', 'data-tip': tooltipText, 'data-for': tooltipId },
                this.renderAddButton()
              ),
              isNotWritableTooltip
            ),
            React.createElement(
              Col,
              { lg: 6, md: 6, sm: 6, xs: 6 },
              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',
                  disabled: !this.props.isWritable,
                  onSelect: this.onActionSelect.bind(this)
                }),
                React.createElement(OptionSelector, {
                  id: 'validation-level-selector',
                  bsSize: 'xs',
                  options: levelOptions,
                  title: levelOptions[this.props.validationLevel],
                  label: 'Validation Level',
                  disabled: !this.props.isWritable,
                  onSelect: this.onLevelSelect.bind(this)
                })
              )
            )
          ),
          React.createElement('hr', null),
          React.createElement(
            Row,
            null,
            React.createElement(
              Col,
              { lg: 12, md: 12, sm: 12, xs: 12 },
              React.createElement(
                Table,
                { className: 'rule-builder-table' },
                React.createElement(
                  'thead',
                  null,
                  React.createElement(
                    'tr',
                    null,
                    React.createElement(
                      'th',
                      { className: 'name-column' },
                      'Field Name'
                    ),
                    React.createElement(
                      'th',
                      { className: 'rule-column' },
                      'Rule'
                    ),
                    React.createElement(
                      'th',
                      { className: 'null-column' },
                      'Nullable'
                    ),
                    React.createElement('th', { className: 'ctrl-column' })
                  )
                ),
                React.createElement(
                  'tbody',
                  null,
                  this.renderRules()
                )
              )
            )
          )
        )
      );
    }
  }]);

  return RuleBuilder;
}(React.Component);

RuleBuilder.propTypes = {
  editState: PropTypes.oneOf(['unmodified', 'modified', 'updating', 'error', 'success']).isRequired,
  validationAction: PropTypes.oneOf(['warn', 'error']).isRequired,
  validationLevel: PropTypes.oneOf(['off', 'moderate', 'strict']).isRequired,
  validationRules: PropTypes.array.isRequired,
  serverVersion: PropTypes.string.isRequired,
  isWritable: PropTypes.bool.isRequired
};

RuleBuilder.displayName = 'RuleBuilder';

module.exports = RuleBuilder;