import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Container, Form } from '@redux-devtools/ui';
import { saveSocketSettings } from '../../actions';
const defaultSchema = {
  type: 'object',
  required: [],
  properties: {
    type: {
      title: 'Connection settings (for getting reports and remote debugging)',
      type: 'string',
      enum: ['disabled', 'custom'],
      enumNames: ['no remote connection', 'use local (custom) server']
    },
    hostname: {
      type: 'string'
    },
    port: {
      type: 'number'
    },
    secure: {
      type: 'boolean'
    }
  }
};
const uiSchema = {
  type: {
    'ui:widget': 'radio'
  }
};
export class Connection extends Component {
  setFormData = (type, changed) => {
    let schema;
    if (type !== 'custom') {
      schema = {
        type: 'object',
        properties: {
          type: defaultSchema.properties.type
        }
      };
    } else {
      schema = defaultSchema;
    }
    return {
      formData: {
        type,
        ...this.props.options
      },
      type,
      schema,
      changed
    };
  };
  state = this.setFormData(this.props.type);
  shouldComponentUpdate(nextProps, nextState) {
    return this.state !== nextState;
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    if (this.props.options !== nextProps.options) {
      this.setState({
        formData: {
          ...nextProps.options,
          type: nextProps.type
        }
      });
    }
  }
  handleSave = data => {
    this.props.saveSettings(data.formData);
    this.setState({
      changed: false
    });
  };
  handleChange = data => {
    const formData = data.formData;
    const type = formData.type;
    if (type !== this.state.type) {
      this.setState(this.setFormData(type, true));
    } else if (!this.state.changed) {
      this.setState({
        changed: true,
        formData
      });
    }
  };
  render() {
    const type = this.state.type || 'disabled';
    const changed = this.state.changed;
    const disabled = type === 'disabled';
    return /*#__PURE__*/React.createElement(Container, null, /*#__PURE__*/React.createElement(Form, {
      primaryButton: changed,
      noSubmit: disabled && !changed,
      submitText: disabled ? 'Disconnect' : 'Connect',
      formData: this.state.formData,
      schema: this.state.schema,
      uiSchema: uiSchema,
      onChange: this.handleChange,
      onSubmit: this.handleSave
    }));
  }
}
const mapStateToProps = state => state.connection;
const actionCreators = {
  saveSettings: saveSocketSettings
};
export default connect(mapStateToProps, actionCreators)(Connection);