"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});

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; }; }();

var _react = require("react");

var _react2 = _interopRequireDefault(_react);

var _Editor = require("react-bootstrap-table/lib/Editor");

var _Editor2 = _interopRequireDefault(_Editor);

var _InsertModal = require("react-bootstrap-table/lib/toolbar/InsertModal");

var _InsertModal2 = _interopRequireDefault(_InsertModal);

var _utils = require("react-jsonschema-form/lib/utils");

var _moment = require("moment");

var _moment2 = _interopRequireDefault(_moment);

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

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; }

function convertFields(cellValue, _ref) {
  var type = _ref.type,
      format = _ref.format,
      def = _ref.default;

  if (cellValue === undefined) {
    return cellValue;
  }

  if (type === "boolean") {
    return cellValue === "true";
  } else if (type === "number") {
    return cellValue !== undefined && cellValue != "" ? parseFloat(cellValue) : "";
  } else if (type === "string" && format === "date-time") {
    if (cellValue === "") {
      return def;
    } else {
      var date = new Date(cellValue);
      return date.toISOString();
    }
  } else if (type === "string" && format === "date") {
    if (cellValue === "") {
      return def;
    } else {
      var _date = moment(cellValue).format("YYYY-MM-DD");
      return _date;
    }
  }
  return cellValue;
}

var CustomInsertModal = function (_Component) {
  _inherits(CustomInsertModal, _Component);

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

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

    _this.handleSaveBtnClick = function () {
      var _this$props = _this.props,
          columns = _this$props.columns,
          onSave = _this$props.onSave,
          formData = _this$props.formData,
          onChange = _this$props.onChange,
          schema = _this$props.schema;
      var required = schema.items.required;


      var newRow = {};
      console.log("columns ", columns);
      columns.forEach(function (column, i) {

        if (!column.name) return;

        var fieldSchema = schema.items.properties[column.field];
        if (!fieldSchema) return;
        console.log("FIELD VALUE ", column.field, " --> ", _this.refs[column.field].value);
        var cellValue = _this.refs[column.field] && _this.refs[column.field].value;
        var convertedFields = convertFields(cellValue, fieldSchema);
        if (convertedFields && convertedFields !== "") {
          newRow[column.field] = convertedFields;
        }
      }, _this);
      newRow['_position'] = formData ? formData.length : 1;
      var requiredFields = [];
      required.forEach(function (item) {
        if (!newRow[item]) {
          requiredFields.push(item);
        }
      });

      console.log('NEW FORM ROW data ', newRow);
      if (requiredFields.length > 0) {
        _this.setState({ errorFields: requiredFields });
      } else {

        // prevent adding data that is already in the table
        if (formData && formData.some(function (v) {
          return (0, _utils.deepEquals)(v, newRow);
        })) {
          return formData;
        } else {
          var finalData = formData ? formData.concat(newRow) : [newRow];
          onChange(finalData);
          onSave(newRow);
          return finalData;
        }
      }
    };

    _this.state = {
      errorFields: []
    };
    return _this;
  }

  _createClass(CustomInsertModal, [{
    key: "render",
    value: function render() {
      var _props = this.props,
          onModalClose = _props.onModalClose,
          onSave = _props.onSave,
          columns = _props.columns,
          validateState = _props.validateState,
          ignoreEditable = _props.ignoreEditable,
          uiSchema = _props.uiSchema,
          fields = _props.registry.fields;
      var tableCols = uiSchema.table.tableCols;


      console.log("props ", this.props);
      var Component = fields['rte'];

      return _react2.default.createElement(_InsertModal2.default, this.props)

      // <div style={ {} } className='modal-content react-bs-table-insert-modal'>
      // <div className="modal-header react-bs-table-inser-modal-header">
      //   <span>
      //     <button type="button" className="close" onClick={ onModalClose }>
      //       <span aria-hidden={true}>x</span>
      //       <span className="sr-only">Close</span>
      //     </button>
      //     <h4>Custom Insert Modal</h4>
      //   </span>
      //   </div>
      //   <div className="modal-body container-fluid">
      //     {console.log('columns i ', columns)}
      //     {
      //         columns.map((column, i) => {
      //           const {
      //             editable,
      //             format,
      //             field,
      //             name,
      //             autoValue,
      //             hiddenOnInsert,
      //             customInsertEditor
      //           } = column;


      //           // return (
      //           //   <div>
      //           //   <label>{ name }</label>
      //           //   <Component ref= {field} schema= {{type: "string"}} uiSchema={{}} onChange={()=>{console.log('changesd ')} } />
      //           //   </div>
      //           // )

      //           //this is done to handle input when a table cell contains an action
      //           if(!name) return;

      //           const attr = {
      //             ref: field,
      //             placeholder: editable.placeholder ? editable.placeholder : name
      //           };

      //           let fieldElement;
      //           const defaultValue = editable.defaultValue || undefined;
      //           if (customInsertEditor) {
      //             const { getElement } = customInsertEditor;
      //             fieldElement = getElement(column, attr, 'form-control', ignoreEditable, defaultValue);
      //           }

      //           // fieldElement = false, means to use default editor when enable custom editor
      //           // Becasuse some users want to have default editor based on some condition.
      //           if (!customInsertEditor || fieldElement === false) {
      //             fieldElement = editor(editable, attr, format, '', defaultValue, ignoreEditable);
      //           }

      //           if (autoValue || hiddenOnInsert || !column.field) {
      //             // when you want same auto generate value
      //             // and not allow edit, for example ID field
      //             return null;
      //           }
      //           let errStyle = {}
      //           const error = this.state.errorFields.includes(field) ?
      //             (<span className='help-block bg-danger'>{name} is required</span>) :
      //             null;
      //             let columnConf = {}
      //             tableCols.forEach(item=> {
      //               if(item.dataField === field) {
      //                 columnConf = item
      //               }
      //             })

      //             if(this.state.errorFields.includes(field)){
      //               errStyle = {
      //                 border: '1px solid red'
      //               }
      //             }

      //             // return (
      //             //   <div className='form-group' key={ field }>
      //             //     <label>{ name } : </label>
      //             //     <input ref={ field } type='text' defaultValue={ '' } />
      //             //     { error }
      //             //   </div>
      //             // );

      //           return (
      //             <div className= {`form-group ${columnConf.modalClassName}`} key={ field }>
      //               <label>{ name }</label>
      //               <span className='help-block bg-danger' style={errStyle}>{ fieldElement }</span>
      //             </div>
      //           );
      //         })
      //     }
      //   </div>
      //   <ul>{this.state.errorFields.map((item, i) => {

      //         let errorTitle = item
      //         columns.forEach(columnItem => {
      //           if(columnItem.field === item) {
      //             errorTitle = columnItem.name ? columnItem.name : item
      //             return;
      //           }})
      //           return (
      //             <li key= {i} className='text-danger'> {errorTitle} is required Myan</li>
      //           )
      //             })}
      //             </ul>
      //   <div className="modal-footer react-bs-table-inser-modal-footer">
      //     <button className='btn btn-default' onClick={ onModalClose }>Close</button>
      //     <button className='btn btn-primary' onClick={ () => this.handleSaveBtnClick(columns, onSave) }>Confirm</button>
      //   </div>
      // </div>
      ;
    }
  }]);

  return CustomInsertModal;
}(_react.Component);

exports.default = CustomInsertModal;