import React, { Component } from 'react';
import isEqual from 'lodash/isEqual';
import AceEditor from '@easyv/react-ace';

export default class SQL extends Component<
  {
    dataConfig: any;
    onChange: (config) => any;
  },
  {
    visible: boolean;
    dataConfig: any;
  }
> {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      dataConfig: {}
    };
  }
  componentDidMount() {
    const { dataConfig = {} } = this.props;
    this.setState({ dataConfig });
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    const { dataConfig = {} } = this.props;
    const nextDataConfig = nextProps.dataConfig || {};
    if (!isEqual(dataConfig, nextDataConfig)) {
      this.setState({
        dataConfig: nextDataConfig
      });
    }
  }

  handleEditorBlur = (event, editor) => {
    event.stopPropagation();
    if (editor) {
      const { dataConfig = {} } = this.props;
      const value = editor.getValue();
      if (!isEqual(value, dataConfig.sql)) {
        this.props.onChange({
          data: {
            ...dataConfig,
            sql: value
          }
        });
      }
    }
  };
  render() {
    const { dataConfig = {} } = this.state;
    const { sql = 'SELECT * FROM ' } = dataConfig;

    return (
      <AceEditor
        className="dark"
        tabSize={2}
        highlightActiveLine={false}
        showGutter={true}
        mode="sql"
        theme="twilight"
        width="100%"
        height="400px"
        name="sql"
        onBlur={this.handleEditorBlur}
        value={sql}
        setOptions={{ wrap: true }}
        defaultValue={sql}
      />
    );
  }
}
