"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

var _react = _interopRequireDefault(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _numeral = _interopRequireDefault(require("numeral"));

var _Icon = _interopRequireDefault(require("@material-ui/core/Icon"));

var _validation = _interopRequireDefault(require("../../helpers/validation"));

var _TooltipComponent = _interopRequireDefault(require("../TooltipComponent"));

var _FormGenerator = require("../FormGenerator");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _extends() { _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; }; return _extends.apply(this, arguments); }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

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

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

/** Textfield Component */
var TextField = /*#__PURE__*/function (_React$Component) {
  _inherits(TextField, _React$Component);

  var _super = _createSuper(TextField);

  function TextField(props) {
    var _this;

    _classCallCheck(this, TextField);

    _this = _super.call(this, props);
    _this.onChange = _this.onChange.bind(_assertThisInitialized(_this)); // this.onBlur = this.onBlur.bind(this);
    // this.onFocus = this.onFocus.bind(this);

    _this.format = _this.format.bind(_assertThisInitialized(_this));
    _this.getFormattedValue = _this.getFormattedValue.bind(_assertThisInitialized(_this));
    _this.state = {
      errorText: props.attributes.errorText || '',
      value: _this.format(props.attributes.value) || _this.format(props.attributes.defaultValue) || ''
    };
    return _this;
  }

  _createClass(TextField, [{
    key: "UNSAFE_componentWillReceiveProps",
    value: function UNSAFE_componentWillReceiveProps(props) {
      this.setState({
        errorText: props.attributes.errorText || '',
        value: this.format(props.attributes.value) || ''
      });
    }
  }, {
    key: "format",
    value: function format(value) {
      var formattedValue = value;
      var props = this.props;
      var formatter = props.formatter;
      var number = (0, _numeral["default"])(value).value() || 0;

      if (props.formatter && props.formatter.func && props.formatter.func.format) {
        number = (0, _numeral["default"])(number)[props.formatter.func.format.name](props.formatter.func.format.value).value();
        formattedValue = number;
      }

      if (formatter) {
        switch (formatter.type) {
          case 'number':
            formattedValue = (0, _numeral["default"])(number).format(formatter.expression);
            break;

          default:
            break;
        }
      }

      return formattedValue;
    }
  }, {
    key: "unformat",
    value: function unformat(value) {
      var unformattedValue = value;
      var props = this.props;
      var formatter = props.formatter;

      if (props.formatter && props.formatter.func && props.formatter.func.unformat) {
        unformattedValue = (0, _numeral["default"])(value)[props.formatter.func.unformat.name](props.formatter.func.unformat.value).value();
      }

      if (formatter) {
        switch (formatter.type) {
          case 'number':
            unformattedValue = (0, _numeral["default"])(unformattedValue).value();
            break;

          default:
            break;
        }
      }

      return unformattedValue;
    }
  }, {
    key: "validate",
    value: function validate(value) {
      var isValid = true;
      var props = this.props;

      if (props.rules && props.rules.validation) {
        for (var i = 0; i < props.rules.validation.length; i += 1) {
          var data = props.rules.validation[i];
          isValid = _validation["default"][data.rule](value, data.value);

          if (!isValid) {
            return {
              isValid: false,
              message: data.message
            };
          }
        }
      }

      return {
        isValid: true,
        message: ''
      };
    }
  }, {
    key: "getFormattedValue",
    value: function getFormattedValue(val) {
      var props = this.props;
      var formatter = props.formatter;
      var value = val;

      if (formatter) {
        switch (formatter.type) {
          case 'number':
            value = (0, _numeral["default"])(val).value();
            break;

          default:
            break;
        }
      }

      return value;
    }
  }, {
    key: "onChange",
    value: function onChange() {
      var props = this.props;

      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }

      var value = args[0].target.value;
      this.setState({
        value: value
      });
      var formattedValue = this.getFormattedValue(value);

      if (typeof props.onChange === 'function') {
        props.onChange(props.control, args[0], formattedValue);
      }
    } // onBlur(...args) {
    //   const props = this.props;
    //   const validator = this.validate(this.format(args[0].target.value));
    //   const formattedValue = this.getFormattedValue(args[0].target.value);
    //   this.setState({
    //     value: this.format(args[0].target.value)
    //   });
    //   if (!validator.isValid) {
    //     this.setState({
    //       errorText: validator.message
    //     });
    //   } else {
    //     this.setState({
    //       errorText: ''
    //     });
    //   }
    //   if (typeof props.onBlur === 'function') {
    //     props.onBlur(props.control, args[0], formattedValue);
    //   }
    // }
    //
    // onFocus(...args) {
    //   const props = this.props;
    //   const formattedValue = this.getFormattedValue(args[0].target.value);
    //   this.setState({
    //     value: this.unformat(args[0].target.value)
    //   });
    //   if (typeof props.onFocus === 'function') {
    //     props.onFocus(props.control, args[0], formattedValue);
    //   }
    // }

  }, {
    key: "getInputProps",
    value: function getInputProps(props) {
      var attributes = props.attributes;

      if (attributes.InputProps) {
        if (attributes.InputProps.InputAdornment) {
          var INPUTADORMENT = props.library.InputAdornment;
          return {
            startAdornment: /*#__PURE__*/_react["default"].createElement(INPUTADORMENT, attributes.InputProps.InputAdornment, attributes.InputProps.InputAdornment.icon ? /*#__PURE__*/_react["default"].createElement(_Icon["default"], null, attributes.InputProps.InputAdornment.icon) : '')
          };
        }
      }

      return {};
    }
  }, {
    key: "render",
    value: function render() {
      var props = this.props;
      var state = this.state;
      var _this$state = this.state,
          value = _this$state.value,
          errorText = _this$state.errorText;
      var TEXTFIELD = props.library[props.component];
      var GRID = props.library.Grid;
      var size = 12;
      return /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement("div", {
        style: {
          display: 'flex'
        }
      }, /*#__PURE__*/_react["default"].createElement(TEXTFIELD, _extends({}, props.attributes, {
        InputProps: this.getInputProps(props),
        value: value,
        error: !!errorText,
        helperText: errorText || '',
        onChange: this.onChange
      })), props.attributes.tooltip && /*#__PURE__*/_react["default"].createElement(_TooltipComponent["default"], {
        tooltip: props.attributes.tooltip
      })), props.control.addform && state.value && state.value <= 10 && /*#__PURE__*/_react["default"].createElement(GRID, {
        item: true,
        xs: size,
        sm: size,
        md: size,
        xl: size,
        lg: size
      }, /*#__PURE__*/_react["default"].createElement(_FormGenerator.FormGenerator, {
        data: this.pannelData,
        library: props.library,
        guid: ""
      })));
    }
  }, {
    key: "pannelData",
    get: function get() {
      var ui = [];

      try {
        var props = this.props;
        var state = this.state;
        var v = state.value;

        if (v && v <= 10) {
          var p = {
            id: 'expansionpannel',
            type: 'expansionpannel',
            props: {
              id: 'expansionpannel',
              style: {
                marginTop: 15
              }
            },
            options: [],
            layout: {
              xs: {
                col: 12
              },
              sm: {
                col: 12
              },
              md: {
                col: 12
              },
              lg: {
                col: 12
              }
            }
          };

          for (var i = 0; i < v; i += 1) {
            var addform = props.control.addform;
            var data = addform.data || [];
            var n = i + 1;
            var t = addform.text;
            var text = addform.shownumber ? "".concat(t, " #").concat(n) : t;
            var guid = addform.guid + n;
            var patch = props.control.patchdata ? props.control.patchdata[guid] || {} : {};
            var k = {
              expansionPanel: {
                defaultExpanded: addform.defaultExpanded || false
              },
              expansionPanelSummary: {
                icon: 'expand_more'
              },
              headerTypography: {
                text: text
              },
              expansionPanelDetails: {
                style: {
                  width: '100%'
                }
              },
              content: {
                guid: guid,
                data: data,
                patch: patch
              }
            };
            p.options.push(k);
          }

          ui.push(p);
        }
      } catch (e) {
        console.log(e);
      }

      return ui;
    }
  }]);

  return TextField;
}(_react["default"].Component);

TextField.propTypes = process.env.NODE_ENV !== "production" ? {
  library: _propTypes["default"].object,
  component: _propTypes["default"].string.isRequired,
  attributes: _propTypes["default"].object,
  control: _propTypes["default"].object,
  option: _propTypes["default"].string.isRequired,
  rules: _propTypes["default"].object,
  formatter: _propTypes["default"].object,
  onChange: _propTypes["default"].func,
  onFocus: _propTypes["default"].func,
  onBlur: _propTypes["default"].func
} : {};
TextField.defaultProps = {
  library: null,
  attributes: null,
  control: null,
  rules: null,
  formatter: null,
  onChange: null,
  onFocus: null,
  onBlur: null
};
var _default = TextField;
exports["default"] = _default;