import {
  ClientDatatableComponent
} from "./chunk-3RTU34A3.js";
import {
  OpenaiService
} from "./chunk-TIV2UYBT.js";
import "./chunk-YWQICJL7.js";
import "./chunk-BP5JJWGC.js";
import "./chunk-IGGXREIH.js";
import {
  LoaderComponent
} from "./chunk-X5XWBDVM.js";
import {
  require_sweetalert2_all
} from "./chunk-KLTWPXW2.js";
import {
  MenuMapService
} from "./chunk-3FLJCSSF.js";
import {
  ToastrService
} from "./chunk-2YLAF7RI.js";
import {
  CommonSharedModule
} from "./chunk-7NQGM4EA.js";
import {
  DefaultValueAccessor,
  FormBuilder,
  FormControlName,
  FormGroupDirective,
  FormsModule,
  NgControlStatus,
  NgControlStatusGroup,
  ReactiveFormsModule,
  TranslatePipe,
  TranslateService,
  Validators,
  ɵNgNoValidate
} from "./chunk-NLYGDKUR.js";
import "./chunk-ZEL7H2AL.js";
import {
  GridApiService
} from "./chunk-P7K2QEDI.js";
import {
  CommonModule,
  DatePipe,
  NgClass,
  NgIf,
  ɵsetClassDebugInfo,
  ɵɵProvidersFeature,
  ɵɵStandaloneFeature,
  ɵɵadvance,
  ɵɵconditional,
  ɵɵdefineComponent,
  ɵɵdirectiveInject,
  ɵɵelement,
  ɵɵelementEnd,
  ɵɵelementStart,
  ɵɵgetCurrentView,
  ɵɵlistener,
  ɵɵnextContext,
  ɵɵpipe,
  ɵɵpipeBind1,
  ɵɵproperty,
  ɵɵpureFunction1,
  ɵɵreference,
  ɵɵrepeater,
  ɵɵrepeaterCreate,
  ɵɵrepeaterTrackByIdentity,
  ɵɵresetView,
  ɵɵrestoreView,
  ɵɵtemplate,
  ɵɵtext,
  ɵɵtextInterpolate,
  ɵɵtextInterpolate1
} from "./chunk-GKZIWABI.js";
import {
  __async,
  __toESM
} from "./chunk-CVWHNZRK.js";

// src/app/@lcp-framework/helpers/common/query-helpers.ts
var EQueryTypes;
(function(EQueryTypes2) {
  EQueryTypes2["select"] = "SELECT";
  EQueryTypes2["insert"] = "INSERT";
  EQueryTypes2["update"] = "UPDATE";
  EQueryTypes2["delete"] = "DELETE";
  EQueryTypes2["alter"] = "ALTER";
  EQueryTypes2["drop"] = "DROP";
  EQueryTypes2["create"] = "CREATED";
  EQueryTypes2["truncate"] = "TRUNCATE";
  EQueryTypes2["unknown"] = "UNKNOWN";
})(EQueryTypes || (EQueryTypes = {}));
function getQueryType(query) {
  if (!query)
    return EQueryTypes.unknown;
  const trimmedQuery = query.trim().toUpperCase();
  const firstWord = trimmedQuery.split(/\s+/)[0];
  switch (firstWord) {
    case "SELECT":
    case "WITH":
      return EQueryTypes.select;
    case "INSERT":
      return EQueryTypes.insert;
    case "UPDATE":
      return EQueryTypes.update;
    case "DELETE":
      return EQueryTypes.delete;
    case "ALTER":
      return EQueryTypes.alter;
    case "DROP":
      return EQueryTypes.drop;
    case "CREATE":
      return EQueryTypes.create;
    case "TRUNCATE":
      return EQueryTypes.truncate;
    default:
      return EQueryTypes.unknown;
  }
}

// src/app/@lcp-framework/pages/query-builder/query-builder.component.ts
var import_sweetalert2 = __toESM(require_sweetalert2_all());
var _c0 = (a0) => ({ "text-danger": a0 });
function QueryBuilderComponent_Conditional_13_For_1_Template(rf, ctx) {
  if (rf & 1) {
    const _r2 = \u0275\u0275getCurrentView();
    \u0275\u0275elementStart(0, "li", 22)(1, "div", 23);
    \u0275\u0275listener("click", function QueryBuilderComponent_Conditional_13_For_1_Template_div_click_1_listener() {
      const table_r3 = \u0275\u0275restoreView(_r2).$implicit;
      const ctx_r3 = \u0275\u0275nextContext(2);
      const queryTextarea_r5 = \u0275\u0275reference(26);
      return \u0275\u0275resetView(ctx_r3.insertTextAtCursor(queryTextarea_r5, table_r3));
    });
    \u0275\u0275text(2);
    \u0275\u0275elementEnd();
    \u0275\u0275elementStart(3, "i", 24);
    \u0275\u0275listener("click", function QueryBuilderComponent_Conditional_13_For_1_Template_i_click_3_listener() {
      const table_r3 = \u0275\u0275restoreView(_r2).$implicit;
      const ctx_r3 = \u0275\u0275nextContext(2);
      return \u0275\u0275resetView(ctx_r3.setQuery(table_r3));
    });
    \u0275\u0275elementEnd()();
  }
  if (rf & 2) {
    const table_r3 = ctx.$implicit;
    \u0275\u0275advance(2);
    \u0275\u0275textInterpolate(table_r3);
  }
}
function QueryBuilderComponent_Conditional_13_Template(rf, ctx) {
  if (rf & 1) {
    \u0275\u0275repeaterCreate(0, QueryBuilderComponent_Conditional_13_For_1_Template, 4, 1, "li", 22, \u0275\u0275repeaterTrackByIdentity);
  }
  if (rf & 2) {
    const ctx_r3 = \u0275\u0275nextContext();
    \u0275\u0275repeater(ctx_r3.filteredTableList);
  }
}
function QueryBuilderComponent_Conditional_14_Template(rf, ctx) {
  if (rf & 1) {
    \u0275\u0275elementStart(0, "div", 25)(1, "p");
    \u0275\u0275text(2, "No table's were found");
    \u0275\u0275elementEnd()();
  }
}
function QueryBuilderComponent_Conditional_33_Template(rf, ctx) {
  if (rf & 1) {
    const _r6 = \u0275\u0275getCurrentView();
    \u0275\u0275elementStart(0, "app-client-datatable", 26);
    \u0275\u0275listener("dataChange", function QueryBuilderComponent_Conditional_33_Template_app_client_datatable_dataChange_0_listener($event) {
      \u0275\u0275restoreView(_r6);
      const ctx_r3 = \u0275\u0275nextContext();
      return \u0275\u0275resetView(ctx_r3.onQueryDataChange($event));
    })("sortChange", function QueryBuilderComponent_Conditional_33_Template_app_client_datatable_sortChange_0_listener($event) {
      \u0275\u0275restoreView(_r6);
      const ctx_r3 = \u0275\u0275nextContext();
      return \u0275\u0275resetView(ctx_r3.onQuerySortChange($event));
    });
    \u0275\u0275elementEnd();
  }
  if (rf & 2) {
    const ctx_r3 = \u0275\u0275nextContext();
    \u0275\u0275property("data", ctx_r3.tempTableResponse)("config", ctx_r3.aiResultTableConfig);
  }
}
function QueryBuilderComponent_Conditional_34_Template(rf, ctx) {
  if (rf & 1) {
    \u0275\u0275elementStart(0, "div", 27);
    \u0275\u0275text(1);
    \u0275\u0275elementEnd();
  }
  if (rf & 2) {
    const ctx_r3 = \u0275\u0275nextContext();
    \u0275\u0275property("ngClass", \u0275\u0275pureFunction1(2, _c0, ctx_r3.isTableError));
    \u0275\u0275advance();
    \u0275\u0275textInterpolate1(" ", ctx_r3.responseMessage, " ");
  }
}
function QueryBuilderComponent_app_loader_35_Template(rf, ctx) {
  if (rf & 1) {
    \u0275\u0275element(0, "app-loader");
  }
}
var _QueryBuilderComponent = class _QueryBuilderComponent {
  constructor(fb, openaiService, translate, commonService, gridApiService, toastr) {
    this.fb = fb;
    this.openaiService = openaiService;
    this.translate = translate;
    this.commonService = commonService;
    this.gridApiService = gridApiService;
    this.toastr = toastr;
    this.tableResponse = [];
    this.tempTableResponse = [];
    this.loading = false;
    this.isTableShow = false;
    this.responseMessage = null;
    this.isTableError = false;
    this.queryType = EQueryTypes.unknown;
    this.aiResultTableConfig = {
      columns: [],
      pageSizes: [5, 10, 25],
      defaultPageSize: 5,
      searchable: true,
      headerConfig: {
        showHeader: true,
        addButton: void 0,
        enableFilter: true,
        enableColumnSelector: true,
        enableExport: true
      }
    };
    this.tableList = [];
    this.filteredTableList = [];
    this.form = this.fb.group({
      query: [null, Validators.required],
      search: [null]
    });
  }
  ngOnInit() {
    this.gridApiService.getAllTables().subscribe({
      next: (res) => {
        if (res.data.length) {
          this.tableList = res.data;
          this.filteredTableList = this.tableList;
        }
      }
    });
  }
  searchTable() {
    this.filteredTableList = this.tableList.filter((tname) => tname.toLowerCase().includes(this.form.controls["search"].value));
  }
  setQuery(tableName) {
    this.form.controls["query"].setValue("select * from " + tableName + ";");
    this.validateQuery();
  }
  validateQuery() {
    this.queryType = getQueryType(this.form.controls["query"].value);
    if (this.queryType === EQueryTypes.unknown) {
      this.toastr.error("Enter a valid Query", "Error");
    } else if (this.queryType === EQueryTypes.select) {
      this.submit();
    } else {
      import_sweetalert2.default.fire({
        icon: "info",
        title: "Are you sure you want to perform this " + this.queryType + " operation?",
        text: "click on confirm to continue",
        showCancelButton: true,
        confirmButtonText: "Confirm",
        padding: "2em"
      }).then((result) => __async(this, null, function* () {
        if (result.value) {
          this.submit();
        }
      }));
    }
  }
  insertTextAtCursor(textarea, textToInsert) {
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    let queryText = this.form.controls["query"].value ?? "";
    const originalText = queryText;
    if (start !== null && end !== null) {
      queryText = originalText.substring(0, start) + textToInsert + originalText.substring(end);
      setTimeout(() => {
        textarea.focus();
        textarea.selectionStart = textarea.selectionEnd = start + textToInsert.length;
      });
    } else {
      queryText += textToInsert;
    }
    this.form.controls["query"].setValue(queryText);
  }
  submit() {
    this.loading = true;
    if (this.form.valid) {
      this.openaiService.getResultFromQuery({ sql: this.form.controls["query"].value, is_query_tool: true }).subscribe({
        next: (res) => {
          this.loading = false;
          if (res.code === 200) {
            this.responseMessage = null;
            this.isTableError = false;
            this.populateTableSchema(res.data);
          } else {
            this.responseMessage = res.data;
            this.isTableError = true;
          }
        },
        error: (err) => {
          this.loading = false;
          this.toastr.error("Failed to execute query", "Error");
        }
      });
    } else {
      this.loading = false;
      this.toastr.error("Enter Query", "Error");
    }
  }
  populateTableSchema(result) {
    if (result.length) {
      let firstColumn = result[0];
      this.aiResultTableConfig.columns = Object.keys(firstColumn).map((key) => ({
        key,
        label: key,
        sortable: true,
        searchable: true
      }));
    }
    this.tableResponse = [];
    this.tableResponse = result;
    this.tempTableResponse = this.tableResponse;
    if (this.queryType === EQueryTypes.select) {
      this.isTableShow = true;
    } else {
      this.isTableShow = false;
      this.responseMessage = "\u2714\uFE0F Query executed successfully";
    }
  }
  onQueryDataChange(data) {
    const itemsToUse = !data || data.length === 0 ? this.tableResponse : data;
    this.tempTableResponse = [...itemsToUse];
  }
  onQuerySortChange(sort) {
    const items = [...this.tempTableResponse];
    items.sort((a, b) => {
      const aVal = a[sort.column];
      const bVal = b[sort.column];
      return sort.direction === "asc" ? aVal > bVal ? 1 : -1 : aVal < bVal ? 1 : -1;
    });
    this.onQueryDataChange(items);
  }
};
_QueryBuilderComponent.\u0275fac = function QueryBuilderComponent_Factory(t) {
  return new (t || _QueryBuilderComponent)(\u0275\u0275directiveInject(FormBuilder), \u0275\u0275directiveInject(OpenaiService), \u0275\u0275directiveInject(TranslateService), \u0275\u0275directiveInject(MenuMapService), \u0275\u0275directiveInject(GridApiService), \u0275\u0275directiveInject(ToastrService));
};
_QueryBuilderComponent.\u0275cmp = /* @__PURE__ */ \u0275\u0275defineComponent({ type: _QueryBuilderComponent, selectors: [["app-query-builder"]], standalone: true, features: [\u0275\u0275ProvidersFeature([DatePipe]), \u0275\u0275StandaloneFeature], decls: 36, vars: 19, consts: [["queryTextarea", ""], [3, "formGroup"], [1, "flex"], [1, "mb-3", "flex", "w-1/4", "flex-col", "border-r", "bg-white", "p-4"], [1, "align-items-center", "mb-4", "flex", "justify-between"], [1, "h-20p", "mb-2", "text-lg", "font-bold"], [1, "w-30", "btn", "btn-primary", "text-xs"], [1, "max-h-tl", "space-y-1"], [1, "my-3"], ["type", "text", "formControlName", "search", "placeholder", "Search Tables", 1, "form-input", "w-full", 3, "input"], [1, "flex", "flex-1", "flex-col", "space-y-4", "overflow-auto", "px-4"], [1, "panel", "mb-3"], [1, "mb-3", "flex", "items-start", "justify-between", "gap-2", "lg:flex-row", "lg:items-center"], [1, "text-lg", "font-semibold", "dark:text-white-light"], [1, "mb-3", "grid", "grid-cols-1"], ["formControlName", "query", 1, "h-150p", "form-input", "w-full", "p-1", "text-xs", "text-gray-600", "placeholder:text-white-dark"], [1, "mb-3", "flex", "justify-end", "gap-3"], ["type", "submit", 1, "w-30", "btn", "btn-success", "text-xs", 3, "click"], [1, "panel", "mt-3"], [1, "panel-body"], [3, "data", "config"], [4, "ngIf"], [1, "align-items-center", "flex", "cursor-pointer", "flex-wrap", "justify-between", "gap-2", "rounded", "p-2", "hover:bg-gray-100"], [1, "w-3/4", 3, "click"], [1, "fa-solid", "fa-play", 3, "click"], [1, "align-items-center", "flex", "justify-center"], [3, "dataChange", "sortChange", "data", "config"], [1, "p-3", 3, "ngClass"]], template: function QueryBuilderComponent_Template(rf, ctx) {
  if (rf & 1) {
    const _r1 = \u0275\u0275getCurrentView();
    \u0275\u0275elementStart(0, "form", 1)(1, "div", 2)(2, "div", 3)(3, "div", 4)(4, "h2", 5);
    \u0275\u0275text(5);
    \u0275\u0275pipe(6, "translate");
    \u0275\u0275elementEnd();
    \u0275\u0275elementStart(7, "button", 6);
    \u0275\u0275text(8);
    \u0275\u0275pipe(9, "translate");
    \u0275\u0275elementEnd()();
    \u0275\u0275elementStart(10, "ul", 7)(11, "div", 8)(12, "input", 9);
    \u0275\u0275listener("input", function QueryBuilderComponent_Template_input_input_12_listener() {
      \u0275\u0275restoreView(_r1);
      return \u0275\u0275resetView(ctx.searchTable());
    });
    \u0275\u0275elementEnd()();
    \u0275\u0275template(13, QueryBuilderComponent_Conditional_13_Template, 2, 0)(14, QueryBuilderComponent_Conditional_14_Template, 3, 0);
    \u0275\u0275elementEnd()();
    \u0275\u0275elementStart(15, "div", 10)(16, "div", 11)(17, "div", 12)(18, "h5", 13);
    \u0275\u0275text(19);
    \u0275\u0275pipe(20, "translate");
    \u0275\u0275elementEnd()();
    \u0275\u0275elementStart(21, "div", 14)(22, "label");
    \u0275\u0275text(23);
    \u0275\u0275pipe(24, "translate");
    \u0275\u0275elementEnd();
    \u0275\u0275element(25, "textarea", 15, 0);
    \u0275\u0275elementEnd();
    \u0275\u0275elementStart(27, "div", 16)(28, "button", 17);
    \u0275\u0275listener("click", function QueryBuilderComponent_Template_button_click_28_listener() {
      \u0275\u0275restoreView(_r1);
      return \u0275\u0275resetView(ctx.validateQuery());
    });
    \u0275\u0275text(29);
    \u0275\u0275pipe(30, "translate");
    \u0275\u0275elementEnd()()();
    \u0275\u0275elementStart(31, "div", 18)(32, "div", 19);
    \u0275\u0275template(33, QueryBuilderComponent_Conditional_33_Template, 1, 2, "app-client-datatable", 20)(34, QueryBuilderComponent_Conditional_34_Template, 2, 4);
    \u0275\u0275elementEnd()()()()();
    \u0275\u0275template(35, QueryBuilderComponent_app_loader_35_Template, 1, 0, "app-loader", 21);
  }
  if (rf & 2) {
    \u0275\u0275property("formGroup", ctx.form);
    \u0275\u0275advance(5);
    \u0275\u0275textInterpolate(\u0275\u0275pipeBind1(6, 9, "tables"));
    \u0275\u0275advance(3);
    \u0275\u0275textInterpolate(\u0275\u0275pipeBind1(9, 11, "export_database"));
    \u0275\u0275advance(5);
    \u0275\u0275conditional(13, ctx.filteredTableList.length ? 13 : 14);
    \u0275\u0275advance(6);
    \u0275\u0275textInterpolate1(" ", \u0275\u0275pipeBind1(20, 13, "query_builder_form"), " ");
    \u0275\u0275advance(4);
    \u0275\u0275textInterpolate(\u0275\u0275pipeBind1(24, 15, "enter_query"));
    \u0275\u0275advance(6);
    \u0275\u0275textInterpolate1(" ", \u0275\u0275pipeBind1(30, 17, "submit"), " ");
    \u0275\u0275advance(4);
    \u0275\u0275conditional(33, ctx.isTableShow ? 33 : ctx.responseMessage ? 34 : -1);
    \u0275\u0275advance(2);
    \u0275\u0275property("ngIf", ctx.loading);
  }
}, dependencies: [CommonModule, NgClass, NgIf, CommonSharedModule, \u0275NgNoValidate, DefaultValueAccessor, NgControlStatus, NgControlStatusGroup, TranslatePipe, FormsModule, ReactiveFormsModule, FormGroupDirective, FormControlName, ClientDatatableComponent, LoaderComponent], styles: ["\n\n.max-h-tl[_ngcontent-%COMP%] {\n  max-height: 60vh;\n  overflow-y: auto;\n}\n.h-20p[_ngcontent-%COMP%] {\n  height: 20px;\n}\n.h-150p[_ngcontent-%COMP%] {\n  height: 150px;\n}\n/*# sourceMappingURL=query-builder.component.css.map */"] });
var QueryBuilderComponent = _QueryBuilderComponent;
(() => {
  (typeof ngDevMode === "undefined" || ngDevMode) && \u0275setClassDebugInfo(QueryBuilderComponent, { className: "QueryBuilderComponent", filePath: "src\\app\\@lcp-framework\\pages\\query-builder\\query-builder.component.ts", lineNumber: 23 });
})();
export {
  QueryBuilderComponent
};
//# sourceMappingURL=chunk-ZHJUORUA.js.map
