"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = exports.ClearFormChangedData = exports.isFormChanged = exports.AllFormResponseData = exports.CurrentFormResponseDataByGuid = exports.ClearFormGeneratorAll = exports.AllFormDataKey = exports.ClearFormGeneratorByGuid = exports.FormGenerator = void 0;

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

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

var _lodash = _interopRequireDefault(require("lodash"));

var _reactFlexboxGrid = require("react-flexbox-grid");

var _moment = _interopRequireDefault(require("moment"));

var _DynamicComponent = require("./DynamicComponent");

var _filter = require("../helpers/filter");

var _mui = _interopRequireDefault(require("../config/mui"));

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

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

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var LIBMap = {
  MUI: {
    map: _mui["default"]
  }
};
var response = {};
var onchangeData = {};

var getFieldValue = function getFieldValue() {
  var a = arguments.length <= 0 ? undefined : arguments[0];
  var type = a.type;
  var value = null;

  switch (type) {
    case 'textfield':
      value = arguments.length <= 2 ? undefined : arguments[2];
      break;

    case 'selectfield':
      value = arguments.length <= 3 ? undefined : arguments[3];
      break;

    case 'toggle':
      value = arguments.length <= 2 ? undefined : arguments[2];
      break;

    case 'autocomplete':
      value = arguments.length <= 1 ? undefined : arguments[1];
      break;

    case 'datetimepicker':
      value = arguments.length <= 1 ? undefined : arguments[1];
      break;

    case 'datepicker':
      value = arguments.length <= 1 ? undefined : arguments[1];
      break;

    case 'timepicker':
      value = arguments.length <= 1 ? undefined : arguments[1];
      break;

    case 'radio':
      value = arguments.length <= 2 ? undefined : arguments[2];
      break;

    case 'checkbox':
      value = arguments.length <= 2 ? undefined : arguments[2];
      break;
    // case 'expansionpannel':
    //   value = args[2];
    //   break;

    case 'textfieldaddform':
      value = arguments.length <= 2 ? undefined : arguments[2];
      break;

    case 'selectfieldaddform':
      value = arguments.length <= 3 ? undefined : arguments[3];
      break;

    case 'signature':
      value = arguments.length <= 1 ? undefined : arguments[1];
      break;

    default:
      value = '';
  }

  return value;
};

var getAllMandatoryFields = function getAllMandatoryFields(fields) {
  var mandatoryFields = [];

  _lodash["default"].each(fields, function (field) {
    if (field.rules) {
      var isMandatory = _lodash["default"].find(field.rules.validation, {
        rule: 'mandatory'
      });

      if (isMandatory) {
        mandatoryFields.push(field);
      }
    }
  });

  return mandatoryFields;
};

var getInitialValues = function getInitialValues(fields) {
  var data = {};

  _lodash["default"].each(fields, function (field) {
    if (field.props.value === undefined) {
      data[field.id] = '';
    } else {
      data[field.id] = field.props.value;
    }
  });

  return data;
};

var getFormatedDate = function getFormatedDate(controls, date) {
  var format = controls.props.format || 'YYYY-MM-DD HH:mm:ss';
  return controls.props.isutc ? _moment["default"].utc(date).format(format) : (0, _moment["default"])(date).format(format);
};

var updateDateRangePickerResponse = function updateDateRangePickerResponse(guid, field) {
  var patch = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
  response[guid][field.props.startdatefieldname] = getFormatedDate(field, response[guid][field.props.startdatefieldname] || (0, _moment["default"])().startOf('day'));
  response[guid][field.props.enddatefieldname] = getFormatedDate(field, response[guid][field.props.enddatefieldname] || (0, _moment["default"])().endOf('day'));

  if (patch) {
    if (patch[field.props.startdatefieldname] !== undefined) {
      response[guid][field.props.startdatefieldname] = getFormatedDate(field, patch[field.props.startdatefieldname]);
    }

    if (patch[field.props.enddatefieldname] !== undefined) {
      response[guid][field.props.enddatefieldname] = getFormatedDate(field, patch[field.props.enddatefieldname]);
    }
  }
};

var handleData = function handleData(guid) {
  for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    args[_key - 1] = arguments[_key];
  }

  var controls = args[0];

  if (controls.id) {
    if (controls.type === 'datetimerangepicker') {
      var picker = args[1];
      response[guid][controls.props.startdatefieldname] = getFormatedDate(controls, picker.startDate);
      response[guid][controls.props.enddatefieldname] = getFormatedDate(controls, picker.endDate);
    } else {
      response[guid][controls.id] = getFieldValue.apply(void 0, args);
    }
  }
};

var updateResponse = function updateResponse(fields, patch, guid) {
  _lodash["default"].each(fields, function (field) {
    if (field.id) {
      if (field.type === 'datetimerangepicker') {
        updateDateRangePickerResponse(guid, field, patch);
      } else if (response[guid][field.id] === '' || response[guid][field.id] === undefined) {
        response[guid][field.id] = field.props.value || field.props.defaultSelected || field.props.defaultChecked || field.props.defaultToggled || field.props.selected || '';

        if (field.props.setdefaultvalueifempty) {
          response[guid][field.id] = _moment["default"].utc().startOf('day').add(7, 'hours').format('YYYY-MM-DD HH:mm:ss');
        }
      } else {// response[guid][field.id] = response[guid][field.id];
      }

      if (patch && patch[field.id] !== undefined) {
        // Patch update data
        response[guid][field.id] = patch[field.id];
      }
    }
  });
};

var getCurrentFormData = function getCurrentFormData(fields, errors, guid) {
  var formData = Object.assign([], fields);

  _lodash["default"].map(formData, function (field) {
    if (field.id) {
      if (field.type.indexOf('selectfield') !== -1) {
        field.props.selected = response[guid][field.id];
      } else if (field.type === 'checkbox') {
        field.props.checked = response[guid][field.id];
      } else if (field.type === 'datetimerangepicker') {
        field.props[field.props.startdatefieldname] = response[guid][field.props.startdatefieldname];
        field.props[field.props.enddatefieldname] = response[guid][field.props.enddatefieldname];
      } else {
        field.props.value = response[guid][field.id];
      }

      var error = _lodash["default"].find(errors, {
        id: field.id
      });

      if (error) {
        field.props.errorText = error.message;
      } else {
        field.props.errorText = '';
      }
    }
  });

  return formData;
};

var getErrors = function getErrors(fields, guid) {
  var mandatoryFields = getAllMandatoryFields(fields);
  var errors = [];

  _lodash["default"].each(mandatoryFields, function (field, index) {
    _lodash["default"].each(field.rules.validation, function (rule) {
      var isClean = _validation["default"][rule.rule](response[guid][field.id].toString(), rule.value);

      if (!isClean) {
        var error = _objectSpread(_objectSpread({}, rule), {}, {
          id: field.id
        });

        errors.push(error);
      }
    });
  });

  return errors;
};

var handleSubmit = function handleSubmit(callback, data, guid) {
  var fields = data;
  var errors = getErrors(data, guid);

  if (typeof callback === 'function') {
    var currentFormData = getCurrentFormData(fields, errors, guid);
    updateResponse(fields, null, guid);
    callback(response, errors, currentFormData);
  }
};
/** FormGenerator */


var FormGenerator = function FormGenerator(props) {
  var config = LIBMap.MUI;
  var forceUpdate = props.forceUpdate,
      library = props.library,
      fetchResponse = props.fetchResponse,
      formRef = props.formRef;
  var data = props.data;
  data = JSON.parse(JSON.stringify(data));

  if (!forceUpdate) {
    var errors = [];

    if (props.displayErrors) {
      errors = getErrors(props.data, props.guid);
    }

    response[props.guid] = response[props.guid] || {};
    updateResponse(props.data, props.patch, props.guid);
    data = getCurrentFormData(props.data, errors, props.guid);
  } else {
    response[props.guid] = response[props.guid] || {};
    response[props.guid] = getInitialValues(data);
  }

  var layout = (0, _filter.generateLayout)(data);
  config.modules = library;
  var guid = props.guid;
  if (guid) onchangeData[guid] = false;
  return /*#__PURE__*/_react["default"].createElement("div", null, layout.wrows.map(function (row, i) {
    return /*#__PURE__*/_react["default"].createElement(_reactFlexboxGrid.Row, {
      key: i
    }, row.map(function (field, index) {
      return /*#__PURE__*/_react["default"].createElement(_reactFlexboxGrid.Col, {
        xs: field.layout.xs ? field.layout.xs.col : 6,
        sm: field.layout.sm ? field.layout.sm.col : 6,
        md: field.layout.md ? field.layout.md.col : 6,
        lg: field.layout.lg ? field.layout.lg.col : 6,
        style: field.style,
        className: "".concat(field.className, " ").concat(field.visible === false ? 'hidden' : 'show'),
        key: index
      }, /*#__PURE__*/_react["default"].createElement(_DynamicComponent.DynamicComponent, {
        component: config.map[field.type].type,
        map: config.map[field.type].map,
        option: config.map[field.type].options ? config.map[field.type].options.type : '',
        control: field,
        library: config.modules,
        attributes: field.props,
        rules: field.rules,
        formatter: field.formatter,
        onChange: function onChange() {
          for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
            args[_key2] = arguments[_key2];
          }

          handleData.apply(void 0, [props.guid].concat(args));

          if (typeof props.onChange === 'function') {
            props.onChange.apply(props, args);
          }

          onchangeData[props.guid] = true;
        },
        onBlur: props.onBlur,
        onFocus: props.onFocus,
        onCheck: function onCheck() {
          for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
            args[_key3] = arguments[_key3];
          }

          handleData.apply(void 0, [props.guid].concat(args));

          if (typeof props.onCheck === 'function') {
            props.onCheck.apply(props, args);
          }

          onchangeData[props.guid] = true;
        },
        onToggle: function onToggle() {
          for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
            args[_key4] = arguments[_key4];
          }

          handleData.apply(void 0, [props.guid].concat(args));

          if (typeof props.onToggle === 'function') {
            props.onToggle.apply(props, args);
          }

          onchangeData[props.guid] = true;
        },
        onShow: props.onShow,
        onDismiss: props.onDismiss,
        onClick: props.onClick,
        onUpdateInput: function onUpdateInput() {
          for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
            args[_key5] = arguments[_key5];
          }

          handleData.apply(void 0, [props.guid].concat(args));

          if (typeof props.onUpdateInput === 'function') {
            props.onUpdateInput.apply(props, args);
          }

          onchangeData[props.guid] = true;
        },
        onNewRequest: props.onNewRequest,
        filter: props.filter,
        onSubmitModel: function onSubmitModel() {
          if (typeof props.onSubmitModel === 'function') {
            props.onSubmitModel.apply(props, arguments);
          }

          onchangeData[props.guid] = true;
        }
      }));
    }));
  }), layout.worows.map(function (field, index) {
    return /*#__PURE__*/_react["default"].createElement("div", {
      key: index,
      style: field.style,
      className: "".concat(field.className, " ").concat(field.visible === false ? 'hidden' : 'show')
    }, /*#__PURE__*/_react["default"].createElement(_DynamicComponent.DynamicComponent, {
      component: config.map[field.type].type,
      map: config.map[field.type].map,
      option: config.map[field.type].options ? config.map[field.type].options.type : '',
      control: field,
      library: config.modules,
      attributes: field.props,
      rules: field.rules,
      formatter: field.formatter,
      fetchResponse: fetchResponse,
      onChange: function onChange() {
        for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
          args[_key6] = arguments[_key6];
        }

        handleData.apply(void 0, [props.guid].concat(args));

        if (typeof props.onChange === 'function') {
          props.onChange.apply(props, args);
        }

        onchangeData[props.guid] = true;
      },
      onBlur: props.onBlur,
      onFocus: props.onFocus,
      onCheck: function onCheck() {
        for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
          args[_key7] = arguments[_key7];
        }

        handleData.apply(void 0, [props.guid].concat(args));

        if (typeof props.onCheck === 'function') {
          props.onCheck.apply(props, args);
        }

        onchangeData[props.guid] = true;
      },
      onToggle: function onToggle() {
        for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
          args[_key8] = arguments[_key8];
        }

        handleData.apply(void 0, [props.guid].concat(args));

        if (typeof props.onToggle === 'function') {
          props.onToggle.apply(props, args);
        }

        onchangeData[props.guid] = true;
      },
      onShow: props.onShow,
      onDismiss: props.onDismiss,
      onClick: props.onClick,
      onUpdateInput: function onUpdateInput() {
        for (var _len9 = arguments.length, args = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) {
          args[_key9] = arguments[_key9];
        }

        handleData.apply(void 0, [props.guid].concat(args));

        if (typeof props.onUpdateInput === 'function') {
          props.onUpdateInput.apply(props, args);
        }

        onchangeData[props.guid] = true;
      },
      onNewRequest: props.onNewRequest,
      onSubmitModel: function onSubmitModel() {
        if (typeof props.onSubmitModel === 'function') {
          props.onSubmitModel.apply(props, arguments);
        }

        onchangeData[props.guid] = true;
      },
      filter: props.filter
    }));
  }), /*#__PURE__*/_react["default"].createElement("button", {
    type: "button",
    ref: formRef,
    onClick: function onClick() {
      handleSubmit(props.onSubmit, data, props.guid);
    },
    style: {
      display: 'none'
    }
  }));
};

exports.FormGenerator = FormGenerator;

var ClearFormGeneratorByGuid = function ClearFormGeneratorByGuid() {
  var guid = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';

  if (guid) {
    delete response[guid];
    delete onchangeData[guid];
  }
};

exports.ClearFormGeneratorByGuid = ClearFormGeneratorByGuid;

var AllFormDataKey = function AllFormDataKey() {
  return Object.keys(response || {});
};

exports.AllFormDataKey = AllFormDataKey;

var ClearFormGeneratorAll = function ClearFormGeneratorAll() {
  var except = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];

  _lodash["default"].map(Object.keys(response), function (k) {
    if (except.indexOf(k) === -1) {
      delete response[k];
    }
  });
};

exports.ClearFormGeneratorAll = ClearFormGeneratorAll;

var CurrentFormResponseDataByGuid = function CurrentFormResponseDataByGuid(guid) {
  if (!response[guid]) {
    return '';
  }

  return response[guid];
};

exports.CurrentFormResponseDataByGuid = CurrentFormResponseDataByGuid;

var AllFormResponseData = function AllFormResponseData() {
  return response;
};

exports.AllFormResponseData = AllFormResponseData;

var isFormChanged = function isFormChanged() {
  var guid = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  if (guid) return onchangeData[guid] || false;
  return onchangeData;
};

exports.isFormChanged = isFormChanged;

var ClearFormChangedData = function ClearFormChangedData() {
  _lodash["default"].map(Object.keys(onchangeData), function (k) {
    delete onchangeData[k];
  });
};

exports.ClearFormChangedData = ClearFormChangedData;
FormGenerator.propTypes = process.env.NODE_ENV !== "production" ? {
  data: _propTypes["default"].array.isRequired,
  library: _propTypes["default"].object,
  onChange: _propTypes["default"].func,
  onFocus: _propTypes["default"].func,
  onBlur: _propTypes["default"].func,
  onClick: _propTypes["default"].func,
  onCheck: _propTypes["default"].func,
  onToggle: _propTypes["default"].func,
  onShow: _propTypes["default"].func,
  onDismiss: _propTypes["default"].func,
  onUpdateInput: _propTypes["default"].func,
  onNewRequest: _propTypes["default"].func,
  filter: _propTypes["default"].func,
  response: _propTypes["default"].object,
  onSubmit: _propTypes["default"].func,
  formRef: _propTypes["default"].func,
  forceUpdate: _propTypes["default"].bool,
  displayErrors: _propTypes["default"].bool,
  patch: _propTypes["default"].object,
  guid: _propTypes["default"].string.isRequired,
  fetchResponse: _propTypes["default"].object,
  onSubmitModel: _propTypes["default"].func
} : {};
FormGenerator.defaultProps = {
  library: null,
  onChange: null,
  onFocus: null,
  onBlur: null,
  onClick: null,
  onCheck: null,
  onToggle: null,
  onShow: null,
  onDismiss: null,
  onUpdateInput: null,
  onNewRequest: null,
  filter: null,
  response: null,
  onSubmit: null,
  formRef: null,
  forceUpdate: null,
  displayErrors: null,
  patch: null,
  fetchResponse: null,
  onSubmitModel: null
};
var _default = {
  FormGenerator: FormGenerator,
  ClearFormGeneratorByGuid: ClearFormGeneratorByGuid,
  ClearFormGeneratorAll: ClearFormGeneratorAll,
  CurrentFormResponseDataByGuid: CurrentFormResponseDataByGuid,
  AllFormResponseData: AllFormResponseData,
  isFormChanged: isFormChanged,
  ClearFormChangedData: ClearFormChangedData,
  AllFormDataKey: AllFormDataKey
};
exports["default"] = _default;