import React from 'react';
import { Dialog, ReactWidget } from '@jupyterlab/apputils';
import { Widget } from '@lumino/widgets';
import { Signal } from '@lumino/signaling';
import DatasyncForm, { ISyncData } from './DatasyncForm';

interface IProps {}

const DatasyncView: React.FunctionComponent<IProps> = props => {
  return (
    <div style={{ flexGrow: 1, display: 'flex', flexDirection: 'column' }}>
      <div
        style={{ display: 'flex', justifyContent: 'flex-end', padding: '10px' }}
      >
        <button
          className="jldbq-btn-add"
          onClick={async () => {
            const body = new DatasyncFormDialogBody();
            const dialog = new Dialog({
              title: '添加同步任务',
              body,
              renderer: new DatasyncFormDialogRenderer()
            });
            body.confirm.connect((_sender, data) => {
              console.log(data);
              dialog.reject();
            });
            body.cancel.connect(() => {
              dialog.reject();
            });
            await dialog.launch();
          }}
        >
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="20"
            height="20"
            fill="currentColor"
            viewBox="0 0 16 16"
          >
            <path d="M8 4a.5.5 0 0 1 .5.5v3h3a.5.5 0 0 1 0 1h-3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3A.5.5 0 0 1 8 4z" />
          </svg>
          添加同步任务
        </button>
      </div>
    </div>
  );
};

export default DatasyncView;

class DatasyncFormDialogBody extends ReactWidget {
  constructor(options?: Widget.IOptions) {
    super(options);
  }

  render(): JSX.Element {
    Signal;
    return (
      <DatasyncForm
        datasourceList={[
          {
            host: '1.1.1.1',
            user: 'user',
            port: 3306,
            password: '',
            charset: 'utf8',
            manager: 'manager',
            source: 'mysql',
            databasename: 'default',
            datasourcename: 'default',
            sourcename: 'default'
          }
        ]}
        tableListFetcher={async () => {
          return ['1', '2', '3'];
        }}
        onConfirm={v => this._confirm.emit(v)}
        onCancel={() => this._cancel.emit()}
      />
    );
  }

  get confirm() {
    return this._confirm;
  }

  get cancel() {
    return this._cancel;
  }

  private _confirm = new Signal<DatasyncFormDialogBody, ISyncData[]>(this);
  private _cancel = new Signal<DatasyncFormDialogBody, void>(this);
}

class DatasyncFormDialogRenderer extends Dialog.Renderer {
  createFooter(_buttons: ReadonlyArray<HTMLElement>): Widget {
    return new Widget();
  }
}
