import React, { useState, useEffect, useCallback } from 'react';
import { useAsync } from 'react-use';
import '@grafana/data';
import { applyQueryDefaults } from './defaults.js';
import { EditorMode } from './types.js';
import { haveColumns } from './utils/sql.utils.js';
import { QueryHeader } from './QueryHeader.js';
import { RawEditor } from './query-editor-raw/RawEditor.js';
import { VisualEditor } from './visual-query-builder/VisualEditor.js';
import '@grafana/runtime';
import { Space } from './Space.js';

function SqlQueryEditor({ datasource, query, onChange, onRunQuery, range, language = "sql" }) {
  var _a, _b, _c, _d, _e, _f, _g;
  const [isQueryRunnable, setIsQueryRunnable] = useState(true);
  const db = datasource.getDB();
  const defaultDataset = datasource.dataset;
  const { loading, error } = useAsync(async () => {
    return () => {
      if (datasource.getDB(datasource.id).init !== undefined) {
        datasource.getDB(datasource.id).init();
      }
    };
  }, [datasource]);
  const queryWithDefaults = applyQueryDefaults(query);
  const [queryRowFilter, setQueryRowFilter] = useState({
    filter: !!((_a = queryWithDefaults.sql) == null ? undefined : _a.whereString),
    group: !!((_d = (_c = (_b = queryWithDefaults.sql) == null ? undefined : _b.groupBy) == null ? undefined : _c[0]) == null ? undefined : _d.property.name),
    order: !!((_f = (_e = queryWithDefaults.sql) == null ? undefined : _e.orderBy) == null ? undefined : _f.property.name),
    preview: true
  });
  const [queryToValidate, setQueryToValidate] = useState(queryWithDefaults);
  useEffect(() => {
    return () => {
      if (datasource.getDB(datasource.id).dispose !== undefined) {
        datasource.getDB(datasource.id).dispose();
      }
    };
  }, [datasource]);
  const processQuery = useCallback(
    (q) => {
      if (isQueryValid(q) && onRunQuery) {
        onRunQuery();
      }
    },
    [onRunQuery]
  );
  const onQueryChange = (q, process = true) => {
    var _a2, _b2;
    setQueryToValidate(q);
    onChange(q);
    if (haveColumns((_a2 = q.sql) == null ? undefined : _a2.columns) && ((_b2 = q.sql) == null ? undefined : _b2.columns.some((c) => c.name)) && !queryRowFilter.group) {
      setQueryRowFilter({ ...queryRowFilter, group: true });
    }
    if (process) {
      processQuery(q);
    }
  };
  const onQueryHeaderChange = (q) => {
    setQueryToValidate(q);
    onChange(q);
  };
  if (loading || error) {
    return null;
  }
  const catalogsEnabled = db.disableCatalogs === false;
  const datasetsEnabled = !db.disableDatasets;
  const effectiveEnableDatasets = catalogsEnabled ? true : datasetsEnabled;
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(
    QueryHeader,
    {
      db,
      defaultDataset: defaultDataset || "",
      enableDatasets: effectiveEnableDatasets,
      enableCatalogs: catalogsEnabled,
      onChange: onQueryHeaderChange,
      onRunQuery,
      onQueryRowChange: setQueryRowFilter,
      queryRowFilter,
      query: queryWithDefaults,
      isQueryRunnable,
      labels: (_g = datasource.getDB(datasource.id)) == null ? undefined : _g.labels
    }
  ), /* @__PURE__ */ React.createElement(Space, { v: 0.5 }), queryWithDefaults.editorMode !== EditorMode.Code && /* @__PURE__ */ React.createElement(
    VisualEditor,
    {
      db,
      query: queryWithDefaults,
      language,
      onChange: (q) => onQueryChange(q, false),
      queryRowFilter,
      onValidate: setIsQueryRunnable,
      range
    }
  ), queryWithDefaults.editorMode === EditorMode.Code && /* @__PURE__ */ React.createElement(
    RawEditor,
    {
      db,
      language,
      query: queryWithDefaults,
      queryToValidate,
      onChange: onQueryChange,
      onRunQuery,
      onValidate: setIsQueryRunnable,
      range
    }
  ));
}
const isQueryValid = (q) => {
  return Boolean(q.rawSql);
};

export { SqlQueryEditor };
//# sourceMappingURL=QueryEditor.js.map
