/**
 * @fileoverview MCP Connection Dialog Component
 *
 * Dialog for creating and editing MCP server connections.
 */
import { Component, Input, Output, EventEmitter, ViewChild } from '@angular/core';
import { Validators } from '@angular/forms';
import { RunView, CompositeKey } from '@memberjunction/core';
import { UUIDsEqual } from '@memberjunction/global';
import { BaseAngularComponent } from '@memberjunction/ng-base-types';
import * as i0 from "@angular/core";
import * as i1 from "@angular/forms";
import * as i2 from "@memberjunction/ng-ui-components";
import * as i3 from "@memberjunction/ng-credentials";
const _c0 = ["credentialDialog"];
const _c1 = () => ({ Name: "Select a server...", ID: "" });
const _c2 = () => ({ standalone: true });
const _c3 = () => ["Active", "Inactive"];
const _c4 = () => ({ Name: "Global (all companies)", ID: "" });
const _c5 = () => ({ Name: "No credential (anonymous)", ID: "" });
function MCPConnectionDialogComponent_Conditional_0_Conditional_2_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "mj-alert", 6);
    i0.ɵɵtext(1);
    i0.ɵɵelementEnd();
} if (rf & 2) {
    const ctx_r1 = i0.ɵɵnextContext(2);
    i0.ɵɵadvance();
    i0.ɵɵtextInterpolate(ctx_r1.ErrorMessage);
} }
function MCPConnectionDialogComponent_Conditional_0_ng_template_13_Conditional_3_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "span", 46);
    i0.ɵɵtext(1);
    i0.ɵɵelementEnd();
} if (rf & 2) {
    const dataItem_r3 = i0.ɵɵnextContext().$implicit;
    i0.ɵɵadvance();
    i0.ɵɵtextInterpolate(dataItem_r3.TransportType);
} }
function MCPConnectionDialogComponent_Conditional_0_ng_template_13_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "div", 44)(1, "span", 45);
    i0.ɵɵtext(2);
    i0.ɵɵelementEnd();
    i0.ɵɵconditionalCreate(3, MCPConnectionDialogComponent_Conditional_0_ng_template_13_Conditional_3_Template, 2, 1, "span", 46);
    i0.ɵɵelementEnd();
} if (rf & 2) {
    const dataItem_r3 = ctx.$implicit;
    i0.ɵɵadvance(2);
    i0.ɵɵtextInterpolate(dataItem_r3.Name);
    i0.ɵɵadvance();
    i0.ɵɵconditional(dataItem_r3.TransportType ? 3 : -1);
} }
function MCPConnectionDialogComponent_Conditional_0_Conditional_15_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "span", 13);
    i0.ɵɵtext(1, "Server selection is required");
    i0.ɵɵelementEnd();
} }
function MCPConnectionDialogComponent_Conditional_0_Conditional_22_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "span", 13);
    i0.ɵɵtext(1, "Name is required");
    i0.ɵɵelementEnd();
} }
function MCPConnectionDialogComponent_Conditional_0_Conditional_44_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "div", 24);
    i0.ɵɵelement(1, "i", 42);
    i0.ɵɵtext(2, " Loading credentials... ");
    i0.ɵɵelementEnd();
} }
function MCPConnectionDialogComponent_Conditional_0_Conditional_45_Template(rf, ctx) { if (rf & 1) {
    const _r4 = i0.ɵɵgetCurrentView();
    i0.ɵɵelementStart(0, "div", 47)(1, "mj-dropdown", 12);
    i0.ɵɵlistener("ValueChange", function MCPConnectionDialogComponent_Conditional_0_Conditional_45_Template_mj_dropdown_ValueChange_1_listener($event) { let tmp_4_0; i0.ɵɵrestoreView(_r4); const ctx_r1 = i0.ɵɵnextContext(2); return i0.ɵɵresetView((tmp_4_0 = ctx_r1.connectionForm.get("CredentialID")) == null ? null : tmp_4_0.setValue($event)); });
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(2, "button", 48);
    i0.ɵɵlistener("click", function MCPConnectionDialogComponent_Conditional_0_Conditional_45_Template_button_click_2_listener() { i0.ɵɵrestoreView(_r4); const ctx_r1 = i0.ɵɵnextContext(2); return i0.ɵɵresetView(ctx_r1.openCredentialDialog()); });
    i0.ɵɵelement(3, "i", 49);
    i0.ɵɵtext(4, " New ");
    i0.ɵɵelementEnd()();
    i0.ɵɵelementStart(5, "span", 21);
    i0.ɵɵtext(6, "Select an existing credential or create a new one");
    i0.ɵɵelementEnd();
} if (rf & 2) {
    let tmp_7_0;
    const ctx_r1 = i0.ɵɵnextContext(2);
    i0.ɵɵadvance();
    i0.ɵɵproperty("Data", ctx_r1.credentials)("ValuePrimitive", true)("DefaultItem", i0.ɵɵpureFunction0(5, _c5))("ngModelOptions", i0.ɵɵpureFunction0(6, _c2))("ngModel", (tmp_7_0 = ctx_r1.connectionForm.get("CredentialID")) == null ? null : tmp_7_0.value);
} }
function MCPConnectionDialogComponent_Conditional_0_Conditional_103_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelement(0, "i", 42);
} }
function MCPConnectionDialogComponent_Conditional_0_Template(rf, ctx) { if (rf & 1) {
    const _r1 = i0.ɵɵgetCurrentView();
    i0.ɵɵelementStart(0, "mj-dialog", 4);
    i0.ɵɵlistener("Close", function MCPConnectionDialogComponent_Conditional_0_Template_mj_dialog_Close_0_listener() { i0.ɵɵrestoreView(_r1); const ctx_r1 = i0.ɵɵnextContext(); return i0.ɵɵresetView(ctx_r1.cancel()); });
    i0.ɵɵelementStart(1, "form", 5);
    i0.ɵɵconditionalCreate(2, MCPConnectionDialogComponent_Conditional_0_Conditional_2_Template, 2, 1, "mj-alert", 6);
    i0.ɵɵelementStart(3, "div", 7)(4, "h3");
    i0.ɵɵelement(5, "i", 8);
    i0.ɵɵtext(6, " Basic Information");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(7, "div", 9)(8, "label", 10);
    i0.ɵɵtext(9, "MCP Server ");
    i0.ɵɵelementStart(10, "span", 11);
    i0.ɵɵtext(11, "*");
    i0.ɵɵelementEnd()();
    i0.ɵɵelementStart(12, "mj-dropdown", 12);
    i0.ɵɵlistener("ValueChange", function MCPConnectionDialogComponent_Conditional_0_Template_mj_dropdown_ValueChange_12_listener($event) { let tmp_3_0; i0.ɵɵrestoreView(_r1); const ctx_r1 = i0.ɵɵnextContext(); (tmp_3_0 = ctx_r1.connectionForm.get("MCPServerID")) == null ? null : tmp_3_0.setValue($event); return i0.ɵɵresetView(ctx_r1.onServerChange()); });
    i0.ɵɵtemplate(13, MCPConnectionDialogComponent_Conditional_0_ng_template_13_Template, 4, 2, "ng-template", null, 0, i0.ɵɵtemplateRefExtractor);
    i0.ɵɵelementEnd();
    i0.ɵɵconditionalCreate(15, MCPConnectionDialogComponent_Conditional_0_Conditional_15_Template, 2, 0, "span", 13);
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(16, "div", 9)(17, "label", 14);
    i0.ɵɵtext(18, "Connection Name ");
    i0.ɵɵelementStart(19, "span", 11);
    i0.ɵɵtext(20, "*");
    i0.ɵɵelementEnd()();
    i0.ɵɵelement(21, "input", 15);
    i0.ɵɵconditionalCreate(22, MCPConnectionDialogComponent_Conditional_0_Conditional_22_Template, 2, 0, "span", 13);
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(23, "div", 9)(24, "label", 16);
    i0.ɵɵtext(25, "Description");
    i0.ɵɵelementEnd();
    i0.ɵɵelement(26, "textarea", 17);
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(27, "div", 9)(28, "label", 18);
    i0.ɵɵtext(29, "Status");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(30, "mj-dropdown", 19);
    i0.ɵɵlistener("ValueChange", function MCPConnectionDialogComponent_Conditional_0_Template_mj_dropdown_ValueChange_30_listener($event) { let tmp_3_0; i0.ɵɵrestoreView(_r1); const ctx_r1 = i0.ɵɵnextContext(); return i0.ɵɵresetView((tmp_3_0 = ctx_r1.connectionForm.get("Status")) == null ? null : tmp_3_0.setValue($event)); });
    i0.ɵɵelementEnd()();
    i0.ɵɵelementStart(31, "div", 9)(32, "label", 20);
    i0.ɵɵtext(33, "Company");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(34, "mj-dropdown", 12);
    i0.ɵɵlistener("ValueChange", function MCPConnectionDialogComponent_Conditional_0_Template_mj_dropdown_ValueChange_34_listener($event) { let tmp_3_0; i0.ɵɵrestoreView(_r1); const ctx_r1 = i0.ɵɵnextContext(); return i0.ɵɵresetView((tmp_3_0 = ctx_r1.connectionForm.get("CompanyID")) == null ? null : tmp_3_0.setValue($event)); });
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(35, "span", 21);
    i0.ɵɵtext(36, "Leave as Global to make this connection available to all companies");
    i0.ɵɵelementEnd()()();
    i0.ɵɵelementStart(37, "div", 7)(38, "h3");
    i0.ɵɵelement(39, "i", 22);
    i0.ɵɵtext(40, " Authentication");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(41, "div", 9)(42, "label", 23);
    i0.ɵɵtext(43, "Credential");
    i0.ɵɵelementEnd();
    i0.ɵɵconditionalCreate(44, MCPConnectionDialogComponent_Conditional_0_Conditional_44_Template, 3, 0, "div", 24)(45, MCPConnectionDialogComponent_Conditional_0_Conditional_45_Template, 7, 7);
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(46, "div", 9)(47, "label", 25);
    i0.ɵɵtext(48, "Custom Header Name");
    i0.ɵɵelementEnd();
    i0.ɵɵelement(49, "input", 26);
    i0.ɵɵelementStart(50, "span", 21);
    i0.ɵɵtext(51, "Override the default header name for API key authentication");
    i0.ɵɵelementEnd()()();
    i0.ɵɵelementStart(52, "div", 7)(53, "h3");
    i0.ɵɵelement(54, "i", 27);
    i0.ɵɵtext(55, " Behavior");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(56, "div", 28)(57, "label", 29);
    i0.ɵɵelement(58, "input", 30);
    i0.ɵɵelementStart(59, "span");
    i0.ɵɵtext(60, "Auto-sync tools on connect");
    i0.ɵɵelementEnd()();
    i0.ɵɵelementStart(61, "span", 21);
    i0.ɵɵtext(62, "Automatically discover and sync available tools when connecting");
    i0.ɵɵelementEnd()()();
    i0.ɵɵelementStart(63, "div", 7)(64, "h3");
    i0.ɵɵelement(65, "i", 31);
    i0.ɵɵtext(66, " Logging");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(67, "div", 28)(68, "label", 29);
    i0.ɵɵelement(69, "input", 32);
    i0.ɵɵelementStart(70, "span");
    i0.ɵɵtext(71, "Enable tool call logging");
    i0.ɵɵelementEnd()();
    i0.ɵɵelementStart(72, "span", 21);
    i0.ɵɵtext(73, "Log all tool executions to the database");
    i0.ɵɵelementEnd()();
    i0.ɵɵelementStart(74, "div", 33)(75, "div", 28)(76, "label", 29);
    i0.ɵɵelement(77, "input", 34);
    i0.ɵɵelementStart(78, "span");
    i0.ɵɵtext(79, "Log input parameters");
    i0.ɵɵelementEnd()()();
    i0.ɵɵelementStart(80, "div", 28)(81, "label", 29);
    i0.ɵɵelement(82, "input", 35);
    i0.ɵɵelementStart(83, "span");
    i0.ɵɵtext(84, "Log output content");
    i0.ɵɵelementEnd()()();
    i0.ɵɵelementStart(85, "div", 9)(86, "label", 36);
    i0.ɵɵtext(87, "Max Output Log Size (bytes)");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(88, "mj-numeric-input", 37);
    i0.ɵɵlistener("ngModelChange", function MCPConnectionDialogComponent_Conditional_0_Template_mj_numeric_input_ngModelChange_88_listener($event) { let tmp_3_0; i0.ɵɵrestoreView(_r1); const ctx_r1 = i0.ɵɵnextContext(); return i0.ɵɵresetView((tmp_3_0 = ctx_r1.connectionForm.get("MaxOutputLogSize")) == null ? null : tmp_3_0.setValue($event)); });
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(89, "span", 21);
    i0.ɵɵtext(90, "Maximum size of output content to log (0 = unlimited, max 10MB)");
    i0.ɵɵelementEnd()()()();
    i0.ɵɵelementStart(91, "div", 7)(92, "h3");
    i0.ɵɵelement(93, "i", 38);
    i0.ɵɵtext(94, " Advanced");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(95, "div", 9)(96, "label", 39);
    i0.ɵɵtext(97, "Environment Variables (JSON)");
    i0.ɵɵelementEnd();
    i0.ɵɵelement(98, "textarea", 40);
    i0.ɵɵelementStart(99, "span", 21);
    i0.ɵɵtext(100, "Additional environment variables for Stdio transport (JSON object)");
    i0.ɵɵelementEnd()()()();
    i0.ɵɵelementStart(101, "mj-dialog-actions")(102, "button", 41);
    i0.ɵɵlistener("click", function MCPConnectionDialogComponent_Conditional_0_Template_button_click_102_listener() { i0.ɵɵrestoreView(_r1); const ctx_r1 = i0.ɵɵnextContext(); return i0.ɵɵresetView(ctx_r1.save()); });
    i0.ɵɵconditionalCreate(103, MCPConnectionDialogComponent_Conditional_0_Conditional_103_Template, 1, 0, "i", 42);
    i0.ɵɵtext(104);
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(105, "button", 43);
    i0.ɵɵlistener("click", function MCPConnectionDialogComponent_Conditional_0_Template_button_click_105_listener() { i0.ɵɵrestoreView(_r1); const ctx_r1 = i0.ɵɵnextContext(); return i0.ɵɵresetView(ctx_r1.cancel()); });
    i0.ɵɵtext(106, "Cancel");
    i0.ɵɵelementEnd()()();
} if (rf & 2) {
    let tmp_11_0;
    let tmp_17_0;
    let tmp_22_0;
    let tmp_24_0;
    let tmp_29_0;
    const ctx_r1 = i0.ɵɵnextContext();
    i0.ɵɵproperty("Visible", true)("Title", ctx_r1.DialogTitle)("Width", 600);
    i0.ɵɵadvance();
    i0.ɵɵproperty("formGroup", ctx_r1.connectionForm);
    i0.ɵɵadvance();
    i0.ɵɵconditional(ctx_r1.ErrorMessage ? 2 : -1);
    i0.ɵɵadvance(10);
    i0.ɵɵproperty("Data", ctx_r1.ActiveServers)("ValuePrimitive", true)("DefaultItem", i0.ɵɵpureFunction0(33, _c1))("ngModelOptions", i0.ɵɵpureFunction0(34, _c2))("ngModel", (tmp_11_0 = ctx_r1.connectionForm.get("MCPServerID")) == null ? null : tmp_11_0.value);
    i0.ɵɵadvance(3);
    i0.ɵɵconditional(ctx_r1.hasError("MCPServerID", "required") ? 15 : -1);
    i0.ɵɵadvance(7);
    i0.ɵɵconditional(ctx_r1.hasError("Name", "required") ? 22 : -1);
    i0.ɵɵadvance(4);
    i0.ɵɵproperty("rows", 3);
    i0.ɵɵadvance(4);
    i0.ɵɵproperty("Data", i0.ɵɵpureFunction0(35, _c3))("ngModelOptions", i0.ɵɵpureFunction0(36, _c2))("ngModel", (tmp_17_0 = ctx_r1.connectionForm.get("Status")) == null ? null : tmp_17_0.value);
    i0.ɵɵadvance(4);
    i0.ɵɵproperty("Data", ctx_r1.companies)("ValuePrimitive", true)("DefaultItem", i0.ɵɵpureFunction0(37, _c4))("ngModelOptions", i0.ɵɵpureFunction0(38, _c2))("ngModel", (tmp_22_0 = ctx_r1.connectionForm.get("CompanyID")) == null ? null : tmp_22_0.value);
    i0.ɵɵadvance(10);
    i0.ɵɵconditional(ctx_r1.IsLoadingDropdowns ? 44 : 45);
    i0.ɵɵadvance(30);
    i0.ɵɵclassProp("disabled", !((tmp_24_0 = ctx_r1.connectionForm.get("LogToolCalls")) == null ? null : tmp_24_0.value));
    i0.ɵɵadvance(14);
    i0.ɵɵproperty("Min", 0)("Max", 10485760)("Step", 10240)("ngModelOptions", i0.ɵɵpureFunction0(39, _c2))("ngModel", (tmp_29_0 = ctx_r1.connectionForm.get("MaxOutputLogSize")) == null ? null : tmp_29_0.value);
    i0.ɵɵadvance(10);
    i0.ɵɵproperty("rows", 3);
    i0.ɵɵadvance(4);
    i0.ɵɵproperty("disabled", ctx_r1.IsSaving);
    i0.ɵɵadvance();
    i0.ɵɵconditional(ctx_r1.IsSaving ? 103 : -1);
    i0.ɵɵadvance();
    i0.ɵɵtextInterpolate1(" ", ctx_r1.IsEditMode ? "Update" : "Create", " ");
} }
function MCPConnectionDialogComponent_Conditional_1_Template(rf, ctx) { if (rf & 1) {
    const _r5 = i0.ɵɵgetCurrentView();
    i0.ɵɵelementStart(0, "mj-credential-dialog", 50, 1);
    i0.ɵɵlistener("close", function MCPConnectionDialogComponent_Conditional_1_Template_mj_credential_dialog_close_0_listener($event) { i0.ɵɵrestoreView(_r5); const ctx_r1 = i0.ɵɵnextContext(); return i0.ɵɵresetView(ctx_r1.onCredentialDialogClose($event)); });
    i0.ɵɵelementEnd();
} if (rf & 2) {
    const ctx_r1 = i0.ɵɵnextContext();
    i0.ɵɵproperty("Visible", ctx_r1.ShowCredentialDialog);
} }
/**
 * MCP Connection Dialog Component
 */
export class MCPConnectionDialogComponent extends BaseAngularComponent {
    fb;
    cdr;
    credentialDialog;
    connection = null;
    servers = [];
    visible = false;
    close = new EventEmitter();
    connectionForm;
    credentials = [];
    companies = [];
    credentialTypes = [];
    IsSaving = false;
    IsLoadingDropdowns = false;
    ErrorMessage = null;
    ShowCredentialDialog = false;
    get IsEditMode() {
        return !!this.connection?.ID;
    }
    get DialogTitle() {
        return this.IsEditMode ? 'Edit Connection' : 'Add Connection';
    }
    get ActiveServers() {
        return this.servers.filter(s => s.Status === 'Active');
    }
    constructor(fb, cdr) {
        super();
        this.fb = fb;
        this.cdr = cdr;
        this.connectionForm = this.createForm();
    }
    ngOnInit() {
        this.loadDropdownData();
    }
    ngOnChanges(changes) {
        if (changes['connection'] || changes['visible']) {
            if (this.visible) {
                this.initializeForm();
            }
        }
    }
    createForm() {
        return this.fb.group({
            MCPServerID: ['', Validators.required],
            Name: ['', [Validators.required, Validators.maxLength(200)]],
            Description: ['', Validators.maxLength(2000)],
            CompanyID: [''],
            CredentialID: [''],
            AutoSyncTools: [true],
            LogToolCalls: [true],
            LogInputParameters: [true],
            LogOutputContent: [true],
            MaxOutputLogSize: [102400, [Validators.min(0), Validators.max(10485760)]],
            CustomHeaderName: [''],
            EnvironmentVars: [''],
            Status: ['Active']
        });
    }
    initializeForm() {
        if (this.connection) {
            this.connectionForm.patchValue({
                MCPServerID: this.connection.MCPServerID,
                Name: this.connection.Name,
                Description: this.connection.Description ?? '',
                CompanyID: this.connection.CompanyID ?? '',
                CredentialID: this.connection.CredentialID ?? '',
                AutoSyncTools: this.connection.AutoSyncTools,
                LogToolCalls: this.connection.LogToolCalls,
                LogInputParameters: true,
                LogOutputContent: true,
                MaxOutputLogSize: 102400,
                CustomHeaderName: '',
                EnvironmentVars: '',
                Status: this.connection.Status
            });
        }
        else {
            this.connectionForm.reset({
                MCPServerID: '',
                Name: '',
                Description: '',
                CompanyID: '',
                CredentialID: '',
                AutoSyncTools: true,
                LogToolCalls: true,
                LogInputParameters: true,
                LogOutputContent: true,
                MaxOutputLogSize: 102400,
                CustomHeaderName: '',
                EnvironmentVars: '',
                Status: 'Active'
            });
        }
        this.ErrorMessage = null;
        this.cdr.detectChanges();
    }
    async loadDropdownData() {
        this.IsLoadingDropdowns = true;
        try {
            const rv = RunView.FromMetadataProvider(this.ProviderToUse);
            // Load credentials, credential types, and companies in parallel
            const [credResult, typeResult, companyResult] = await rv.RunViews([
                {
                    EntityName: 'MJ: Credentials',
                    Fields: ['ID', 'Name'],
                    OrderBy: 'Name',
                    ResultType: 'simple'
                },
                {
                    EntityName: 'MJ: Credential Types',
                    OrderBy: 'Category, Name',
                    ResultType: 'entity_object'
                },
                {
                    EntityName: 'MJ: Companies',
                    Fields: ['ID', 'Name'],
                    OrderBy: 'Name',
                    ResultType: 'simple'
                }
            ]);
            if (credResult.Success) {
                this.credentials = credResult.Results || [];
            }
            if (typeResult.Success) {
                this.credentialTypes = typeResult.Results || [];
            }
            if (companyResult.Success) {
                this.companies = companyResult.Results || [];
            }
        }
        catch (error) {
            console.error('Failed to load dropdown data:', error);
        }
        finally {
            this.IsLoadingDropdowns = false;
            this.cdr.detectChanges();
        }
    }
    /**
     * Opens the credential creation dialog
     */
    openCredentialDialog() {
        this.ShowCredentialDialog = true;
        this.cdr.detectChanges();
    }
    /**
     * Handles the credential dialog close event
     */
    onCredentialDialogClose(result) {
        this.ShowCredentialDialog = false;
        if (result.success && result.credential) {
            // Add the new credential to the list and select it
            this.credentials.push({
                ID: result.credential.ID,
                Name: result.credential.Name
            });
            // Sort credentials by name
            this.credentials.sort((a, b) => a.Name.localeCompare(b.Name));
            // Select the new credential
            this.connectionForm.patchValue({
                CredentialID: result.credential.ID
            });
        }
        this.cdr.detectChanges();
    }
    onServerChange() {
        const serverId = this.connectionForm.get('MCPServerID')?.value;
        const server = this.servers.find(s => UUIDsEqual(s.ID, serverId));
        if (server && !this.connectionForm.get('Name')?.value) {
            // Auto-fill name based on server
            this.connectionForm.patchValue({
                Name: `${server.Name} Connection`
            });
        }
    }
    async save() {
        if (this.connectionForm.invalid) {
            this.connectionForm.markAllAsTouched();
            return;
        }
        this.IsSaving = true;
        this.ErrorMessage = null;
        this.cdr.detectChanges();
        try {
            const md = this.ProviderToUse;
            const entity = await md.GetEntityObject('MJ: MCP Server Connections');
            if (this.IsEditMode && this.connection) {
                await entity.InnerLoad(new CompositeKey([{ FieldName: 'ID', Value: this.connection.ID }]));
            }
            else {
                entity.NewRecord();
            }
            // Apply form values
            const formValue = this.connectionForm.value;
            entity.MCPServerID = formValue.MCPServerID;
            entity.Name = formValue.Name;
            entity.Description = formValue.Description || null;
            entity.CompanyID = formValue.CompanyID || null;
            entity.CredentialID = formValue.CredentialID || null;
            entity.AutoSyncTools = formValue.AutoSyncTools;
            entity.LogToolCalls = formValue.LogToolCalls;
            entity.LogInputParameters = formValue.LogInputParameters;
            entity.LogOutputContent = formValue.LogOutputContent;
            entity.MaxOutputLogSize = formValue.MaxOutputLogSize || 102400;
            entity.CustomHeaderName = formValue.CustomHeaderName || null;
            entity.EnvironmentVars = formValue.EnvironmentVars || null;
            entity.Status = formValue.Status;
            const saved = await entity.Save();
            if (!saved) {
                // Use CompleteMessage for full error details, fall back to Message
                const errorMessage = entity.LatestResult?.CompleteMessage || entity.LatestResult?.Message || 'Unknown error';
                console.error('MCP Connection save failed:', errorMessage, entity.LatestResult);
                throw new Error(errorMessage);
            }
            this.close.emit({ saved: true });
        }
        catch (error) {
            const errorMsg = error instanceof Error ? error.message : String(error);
            this.ErrorMessage = `Failed to save: ${errorMsg}`;
            console.error('MCP Connection save error:', errorMsg);
            this.cdr.detectChanges();
        }
        finally {
            this.IsSaving = false;
            this.cdr.detectChanges();
        }
    }
    cancel() {
        this.close.emit({ saved: false });
    }
    hasError(controlName, errorType) {
        const control = this.connectionForm.get(controlName);
        return control?.hasError(errorType) && control?.touched || false;
    }
    static ɵfac = function MCPConnectionDialogComponent_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || MCPConnectionDialogComponent)(i0.ɵɵdirectiveInject(i1.FormBuilder), i0.ɵɵdirectiveInject(i0.ChangeDetectorRef)); };
    static ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent({ type: MCPConnectionDialogComponent, selectors: [["mj-mcp-connection-dialog"]], viewQuery: function MCPConnectionDialogComponent_Query(rf, ctx) { if (rf & 1) {
            i0.ɵɵviewQuery(_c0, 5);
        } if (rf & 2) {
            let _t;
            i0.ɵɵqueryRefresh(_t = i0.ɵɵloadQuery()) && (ctx.credentialDialog = _t.first);
        } }, inputs: { connection: "connection", servers: "servers", visible: "visible" }, outputs: { close: "close" }, standalone: false, features: [i0.ɵɵInheritDefinitionFeature, i0.ɵɵNgOnChangesFeature], decls: 2, vars: 2, consts: [["mjDropdownItem", ""], ["credentialDialog", ""], [3, "Visible", "Title", "Width"], [3, "Visible"], [3, "Close", "Visible", "Title", "Width"], [1, "connection-form", 3, "formGroup"], ["Variant", "error"], [1, "form-section"], [1, "fa-solid", "fa-info-circle"], [1, "form-group"], ["for", "server"], [1, "required"], ["TextField", "Name", "ValueField", "ID", 3, "ValueChange", "Data", "ValuePrimitive", "DefaultItem", "ngModelOptions", "ngModel"], [1, "error-text"], ["for", "name"], ["id", "name", "formControlName", "Name", "placeholder", "e.g., Production GitHub Connection", 1, "mj-input"], ["for", "description"], ["id", "description", "formControlName", "Description", "placeholder", "Optional description of this connection", 1, "mj-textarea", 3, "rows"], ["for", "status"], [3, "ValueChange", "Data", "ngModelOptions", "ngModel"], ["for", "company"], [1, "hint"], [1, "fa-solid", "fa-key"], ["for", "credential"], [1, "loading-credentials"], ["for", "customHeader"], ["id", "customHeader", "formControlName", "CustomHeaderName", "placeholder", "e.g., X-Custom-API-Key", 1, "mj-input"], [1, "fa-solid", "fa-sliders"], [1, "checkbox-group"], [1, "checkbox-label"], ["type", "checkbox", "formControlName", "AutoSyncTools", 1, "mj-checkbox"], [1, "fa-solid", "fa-file-lines"], ["type", "checkbox", "formControlName", "LogToolCalls", 1, "mj-checkbox"], [1, "logging-options"], ["type", "checkbox", "formControlName", "LogInputParameters", 1, "mj-checkbox"], ["type", "checkbox", "formControlName", "LogOutputContent", 1, "mj-checkbox"], ["for", "maxOutputSize"], [3, "ngModelChange", "Min", "Max", "Step", "ngModelOptions", "ngModel"], [1, "fa-solid", "fa-gear"], ["for", "envVars"], ["id", "envVars", "formControlName", "EnvironmentVars", "placeholder", "{\"VAR_NAME\": \"value\"}", 1, "mj-textarea", 3, "rows"], ["mjButton", "", "variant", "primary", 3, "click", "disabled"], [1, "fa-solid", "fa-spinner", "fa-spin"], ["mjButton", "", 3, "click"], [1, "server-option"], [1, "server-name"], [1, "server-transport"], [1, "credential-row"], ["mjButton", "", "type", "button", "variant", "outline", "title", "Create New Credential", 3, "click"], [1, "fa-solid", "fa-plus"], [3, "close", "Visible"]], template: function MCPConnectionDialogComponent_Template(rf, ctx) { if (rf & 1) {
            i0.ɵɵconditionalCreate(0, MCPConnectionDialogComponent_Conditional_0_Template, 107, 40, "mj-dialog", 2);
            i0.ɵɵconditionalCreate(1, MCPConnectionDialogComponent_Conditional_1_Template, 2, 1, "mj-credential-dialog", 3);
        } if (rf & 2) {
            i0.ɵɵconditional(ctx.visible ? 0 : -1);
            i0.ɵɵadvance();
            i0.ɵɵconditional(ctx.ShowCredentialDialog ? 1 : -1);
        } }, dependencies: [i1.ɵNgNoValidate, i1.DefaultValueAccessor, i1.CheckboxControlValueAccessor, i1.NgControlStatus, i1.NgControlStatusGroup, i1.NgModel, i1.FormGroupDirective, i1.FormControlName, i2.MJButtonDirective, i2.MJDialogComponent, i2.MJDialogActionsComponent, i2.MJDropdownComponent, i2.MJNumericInputComponent, i2.MJAlertComponent, i3.CredentialDialogComponent], styles: [".connection-form[_ngcontent-%COMP%] {\n    display: flex;\n    flex-direction: column;\n    gap: 20px;\n}\n\n.form-section[_ngcontent-%COMP%] {\n    border: 1px solid var(--mj-border-default);\n    border-radius: 8px;\n    padding: 16px;\n}\n\n.form-section[_ngcontent-%COMP%]   h3[_ngcontent-%COMP%] {\n    display: flex;\n    align-items: center;\n    gap: 8px;\n    margin: 0 0 16px 0;\n    font-size: 14px;\n    font-weight: 600;\n    color: var(--mj-text-primary);\n}\n\n.form-section[_ngcontent-%COMP%]   h3[_ngcontent-%COMP%]   i[_ngcontent-%COMP%] {\n    color: var(--mj-brand-primary);\n}\n\n.form-group[_ngcontent-%COMP%] {\n    margin-bottom: 16px;\n}\n\n.form-group[_ngcontent-%COMP%]:last-child {\n    margin-bottom: 0;\n}\n\n.form-group[_ngcontent-%COMP%]   label[_ngcontent-%COMP%] {\n    display: block;\n    margin-bottom: 6px;\n    font-size: 13px;\n    font-weight: 500;\n    color: var(--mj-text-primary);\n}\n\n.form-group[_ngcontent-%COMP%]   label[_ngcontent-%COMP%]   .required[_ngcontent-%COMP%] {\n    color: var(--mj-status-error);\n}\n\n.form-group[_ngcontent-%COMP%]   input[_ngcontent-%COMP%], \n.form-group[_ngcontent-%COMP%]   textarea[_ngcontent-%COMP%] {\n    width: 100%;\n}\n\n.form-group[_ngcontent-%COMP%]   .hint[_ngcontent-%COMP%] {\n    display: block;\n    margin-top: 4px;\n    font-size: 12px;\n    color: var(--mj-text-disabled);\n}\n\n.form-group[_ngcontent-%COMP%]   .error-text[_ngcontent-%COMP%] {\n    display: block;\n    margin-top: 4px;\n    font-size: 12px;\n    color: var(--mj-status-error);\n}\n\n.server-option[_ngcontent-%COMP%] {\n    display: flex;\n    justify-content: space-between;\n    align-items: center;\n    width: 100%;\n}\n\n.server-name[_ngcontent-%COMP%] {\n    font-weight: 500;\n}\n\n.server-transport[_ngcontent-%COMP%] {\n    font-size: 12px;\n    color: var(--mj-text-muted);\n    padding: 2px 8px;\n    background: var(--mj-bg-surface-card);\n    border-radius: 4px;\n}\n\n.loading-credentials[_ngcontent-%COMP%] {\n    display: flex;\n    align-items: center;\n    gap: 8px;\n    padding: 8px 12px;\n    background: var(--mj-bg-surface-card);\n    border-radius: 6px;\n    color: var(--mj-text-muted);\n    font-size: 14px;\n}\n\n.credential-row[_ngcontent-%COMP%] {\n    display: flex;\n    align-items: center;\n    gap: 8px;\n}\n\n.credential-row[_ngcontent-%COMP%]   button[_ngcontent-%COMP%] {\n    white-space: nowrap;\n}\n\n.checkbox-group[_ngcontent-%COMP%] {\n    margin-bottom: 12px;\n}\n\n.checkbox-group[_ngcontent-%COMP%]:last-child {\n    margin-bottom: 0;\n}\n\n.checkbox-label[_ngcontent-%COMP%] {\n    display: flex;\n    align-items: center;\n    gap: 8px;\n    cursor: pointer;\n    font-size: 14px;\n}\n\n.checkbox-group[_ngcontent-%COMP%]   .hint[_ngcontent-%COMP%] {\n    display: block;\n    margin-top: 4px;\n    margin-left: 24px;\n    font-size: 12px;\n    color: var(--mj-text-disabled);\n}\n\n.logging-options[_ngcontent-%COMP%] {\n    margin-top: 16px;\n    padding: 12px;\n    background: var(--mj-bg-surface-card);\n    border-radius: 6px;\n    transition: opacity 0.2s ease;\n}\n\n.logging-options.disabled[_ngcontent-%COMP%] {\n    opacity: 0.5;\n    pointer-events: none;\n}"] });
}
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(MCPConnectionDialogComponent, [{
        type: Component,
        args: [{ standalone: false, selector: 'mj-mcp-connection-dialog', template: "@if (visible) {\n  <mj-dialog\n    [Visible]=\"true\"\n    [Title]=\"DialogTitle\"\n    (Close)=\"cancel()\"\n    [Width]=\"600\">\n    <form [formGroup]=\"connectionForm\" class=\"connection-form\">\n      <!-- Error Message -->\n      @if (ErrorMessage) {\n        <mj-alert Variant=\"error\">{{ ErrorMessage }}</mj-alert>\n      }\n      <!-- Basic Info Section -->\n      <div class=\"form-section\">\n        <h3><i class=\"fa-solid fa-info-circle\"></i> Basic Information</h3>\n        <div class=\"form-group\">\n          <label for=\"server\">MCP Server <span class=\"required\">*</span></label>\n          <mj-dropdown\n            [Data]=\"ActiveServers\"\n            TextField=\"Name\"\n            ValueField=\"ID\"\n            [ValuePrimitive]=\"true\"\n            [DefaultItem]=\"{ Name: 'Select a server...', ID: '' }\"\n            [ngModelOptions]=\"{standalone: true}\" [ngModel]=\"connectionForm.get('MCPServerID')?.value\"\n            (ValueChange)=\"connectionForm.get('MCPServerID')?.setValue($any($event)); onServerChange()\">\n            <ng-template #mjDropdownItem let-dataItem>\n              <div class=\"server-option\">\n                <span class=\"server-name\">{{ dataItem.Name }}</span>\n                @if (dataItem.TransportType) {\n                  <span class=\"server-transport\">{{ dataItem.TransportType }}</span>\n                }\n              </div>\n            </ng-template>\n          </mj-dropdown>\n          @if (hasError('MCPServerID', 'required')) {\n            <span class=\"error-text\">Server selection is required</span>\n          }\n        </div>\n        <div class=\"form-group\">\n          <label for=\"name\">Connection Name <span class=\"required\">*</span></label>\n          <input class=\"mj-input\"\n            id=\"name\"\n            formControlName=\"Name\"\n            placeholder=\"e.g., Production GitHub Connection\" />\n          @if (hasError('Name', 'required')) {\n            <span class=\"error-text\">Name is required</span>\n          }\n        </div>\n        <div class=\"form-group\">\n          <label for=\"description\">Description</label>\n          <textarea class=\"mj-textarea\"\n            id=\"description\"\n            formControlName=\"Description\"\n            placeholder=\"Optional description of this connection\"\n          [rows]=\"3\"></textarea>\n        </div>\n        <div class=\"form-group\">\n          <label for=\"status\">Status</label>\n          <mj-dropdown\n            [Data]=\"['Active', 'Inactive']\"\n            [ngModelOptions]=\"{standalone: true}\" [ngModel]=\"connectionForm.get('Status')?.value\"\n            (ValueChange)=\"connectionForm.get('Status')?.setValue($any($event))\">\n          </mj-dropdown>\n        </div>\n        <div class=\"form-group\">\n          <label for=\"company\">Company</label>\n          <mj-dropdown\n            [Data]=\"companies\"\n            TextField=\"Name\"\n            ValueField=\"ID\"\n            [ValuePrimitive]=\"true\"\n            [DefaultItem]=\"{ Name: 'Global (all companies)', ID: '' }\"\n            [ngModelOptions]=\"{standalone: true}\" [ngModel]=\"connectionForm.get('CompanyID')?.value\"\n            (ValueChange)=\"connectionForm.get('CompanyID')?.setValue($any($event))\">\n          </mj-dropdown>\n          <span class=\"hint\">Leave as Global to make this connection available to all companies</span>\n        </div>\n      </div>\n      <!-- Authentication Section -->\n      <div class=\"form-section\">\n        <h3><i class=\"fa-solid fa-key\"></i> Authentication</h3>\n        <div class=\"form-group\">\n          <label for=\"credential\">Credential</label>\n          @if (IsLoadingDropdowns) {\n            <div class=\"loading-credentials\">\n              <i class=\"fa-solid fa-spinner fa-spin\"></i>\n              Loading credentials...\n            </div>\n          } @else {\n            <div class=\"credential-row\">\n              <mj-dropdown\n                [Data]=\"credentials\"\n                TextField=\"Name\"\n                ValueField=\"ID\"\n                [ValuePrimitive]=\"true\"\n                [DefaultItem]=\"{ Name: 'No credential (anonymous)', ID: '' }\"\n                [ngModelOptions]=\"{standalone: true}\" [ngModel]=\"connectionForm.get('CredentialID')?.value\"\n                (ValueChange)=\"connectionForm.get('CredentialID')?.setValue($any($event))\">\n              </mj-dropdown>\n              <button mjButton\n                type=\"button\"\n                variant=\"outline\"\n                (click)=\"openCredentialDialog()\"\n                title=\"Create New Credential\">\n                <i class=\"fa-solid fa-plus\"></i>\n                New\n              </button>\n            </div>\n            <span class=\"hint\">Select an existing credential or create a new one</span>\n          }\n        </div>\n        <div class=\"form-group\">\n          <label for=\"customHeader\">Custom Header Name</label>\n          <input class=\"mj-input\"\n            id=\"customHeader\"\n            formControlName=\"CustomHeaderName\"\n            placeholder=\"e.g., X-Custom-API-Key\" />\n          <span class=\"hint\">Override the default header name for API key authentication</span>\n        </div>\n      </div>\n      <!-- Behavior Section -->\n      <div class=\"form-section\">\n        <h3><i class=\"fa-solid fa-sliders\"></i> Behavior</h3>\n        <div class=\"checkbox-group\">\n          <label class=\"checkbox-label\">\n            <input type=\"checkbox\" class=\"mj-checkbox\" formControlName=\"AutoSyncTools\" />\n            <span>Auto-sync tools on connect</span>\n          </label>\n          <span class=\"hint\">Automatically discover and sync available tools when connecting</span>\n        </div>\n      </div>\n      <!-- Logging Section -->\n      <div class=\"form-section\">\n        <h3><i class=\"fa-solid fa-file-lines\"></i> Logging</h3>\n        <div class=\"checkbox-group\">\n          <label class=\"checkbox-label\">\n            <input type=\"checkbox\" class=\"mj-checkbox\" formControlName=\"LogToolCalls\" />\n            <span>Enable tool call logging</span>\n          </label>\n          <span class=\"hint\">Log all tool executions to the database</span>\n        </div>\n        <div class=\"logging-options\" [class.disabled]=\"!connectionForm.get('LogToolCalls')?.value\">\n          <div class=\"checkbox-group\">\n            <label class=\"checkbox-label\">\n              <input type=\"checkbox\" class=\"mj-checkbox\" formControlName=\"LogInputParameters\" />\n              <span>Log input parameters</span>\n            </label>\n          </div>\n          <div class=\"checkbox-group\">\n            <label class=\"checkbox-label\">\n              <input type=\"checkbox\" class=\"mj-checkbox\" formControlName=\"LogOutputContent\" />\n              <span>Log output content</span>\n            </label>\n          </div>\n          <div class=\"form-group\">\n            <label for=\"maxOutputSize\">Max Output Log Size (bytes)</label>\n            <mj-numeric-input\n              [Min]=\"0\"\n              [Max]=\"10485760\"\n              [Step]=\"10240\"\n              [ngModelOptions]=\"{standalone: true}\" [ngModel]=\"connectionForm.get('MaxOutputLogSize')?.value\"\n              (ngModelChange)=\"connectionForm.get('MaxOutputLogSize')?.setValue($event)\">\n            </mj-numeric-input>\n            <span class=\"hint\">Maximum size of output content to log (0 = unlimited, max 10MB)</span>\n          </div>\n        </div>\n      </div>\n      <!-- Advanced Section -->\n      <div class=\"form-section\">\n        <h3><i class=\"fa-solid fa-gear\"></i> Advanced</h3>\n        <div class=\"form-group\">\n          <label for=\"envVars\">Environment Variables (JSON)</label>\n          <textarea class=\"mj-textarea\"\n            id=\"envVars\"\n            formControlName=\"EnvironmentVars\"\n            placeholder='{\"VAR_NAME\": \"value\"}'\n          [rows]=\"3\"></textarea>\n          <span class=\"hint\">Additional environment variables for Stdio transport (JSON object)</span>\n        </div>\n      </div>\n    </form>\n    <mj-dialog-actions>\n      <button mjButton variant=\"primary\" (click)=\"save()\" [disabled]=\"IsSaving\">\n        @if (IsSaving) {\n          <i class=\"fa-solid fa-spinner fa-spin\"></i>\n        }\n        {{ IsEditMode ? 'Update' : 'Create' }}\n      </button>\n      <button mjButton (click)=\"cancel()\">Cancel</button>\n    </mj-dialog-actions>\n  </mj-dialog>\n}\n\n<!-- Credential Creation Dialog -->\n@if (ShowCredentialDialog) {\n  <mj-credential-dialog\n    #credentialDialog\n    [Visible]=\"ShowCredentialDialog\"\n    (close)=\"onCredentialDialogClose($event)\">\n  </mj-credential-dialog>\n}\n", styles: [".connection-form {\n    display: flex;\n    flex-direction: column;\n    gap: 20px;\n}\n\n.form-section {\n    border: 1px solid var(--mj-border-default);\n    border-radius: 8px;\n    padding: 16px;\n}\n\n.form-section h3 {\n    display: flex;\n    align-items: center;\n    gap: 8px;\n    margin: 0 0 16px 0;\n    font-size: 14px;\n    font-weight: 600;\n    color: var(--mj-text-primary);\n}\n\n.form-section h3 i {\n    color: var(--mj-brand-primary);\n}\n\n.form-group {\n    margin-bottom: 16px;\n}\n\n.form-group:last-child {\n    margin-bottom: 0;\n}\n\n.form-group label {\n    display: block;\n    margin-bottom: 6px;\n    font-size: 13px;\n    font-weight: 500;\n    color: var(--mj-text-primary);\n}\n\n.form-group label .required {\n    color: var(--mj-status-error);\n}\n\n.form-group input,\n.form-group textarea {\n    width: 100%;\n}\n\n.form-group .hint {\n    display: block;\n    margin-top: 4px;\n    font-size: 12px;\n    color: var(--mj-text-disabled);\n}\n\n.form-group .error-text {\n    display: block;\n    margin-top: 4px;\n    font-size: 12px;\n    color: var(--mj-status-error);\n}\n\n.server-option {\n    display: flex;\n    justify-content: space-between;\n    align-items: center;\n    width: 100%;\n}\n\n.server-name {\n    font-weight: 500;\n}\n\n.server-transport {\n    font-size: 12px;\n    color: var(--mj-text-muted);\n    padding: 2px 8px;\n    background: var(--mj-bg-surface-card);\n    border-radius: 4px;\n}\n\n.loading-credentials {\n    display: flex;\n    align-items: center;\n    gap: 8px;\n    padding: 8px 12px;\n    background: var(--mj-bg-surface-card);\n    border-radius: 6px;\n    color: var(--mj-text-muted);\n    font-size: 14px;\n}\n\n.credential-row {\n    display: flex;\n    align-items: center;\n    gap: 8px;\n}\n\n.credential-row button {\n    white-space: nowrap;\n}\n\n.checkbox-group {\n    margin-bottom: 12px;\n}\n\n.checkbox-group:last-child {\n    margin-bottom: 0;\n}\n\n.checkbox-label {\n    display: flex;\n    align-items: center;\n    gap: 8px;\n    cursor: pointer;\n    font-size: 14px;\n}\n\n.checkbox-group .hint {\n    display: block;\n    margin-top: 4px;\n    margin-left: 24px;\n    font-size: 12px;\n    color: var(--mj-text-disabled);\n}\n\n.logging-options {\n    margin-top: 16px;\n    padding: 12px;\n    background: var(--mj-bg-surface-card);\n    border-radius: 6px;\n    transition: opacity 0.2s ease;\n}\n\n.logging-options.disabled {\n    opacity: 0.5;\n    pointer-events: none;\n}\n\n"] }]
    }], () => [{ type: i1.FormBuilder }, { type: i0.ChangeDetectorRef }], { credentialDialog: [{
            type: ViewChild,
            args: ['credentialDialog']
        }], connection: [{
            type: Input
        }], servers: [{
            type: Input
        }], visible: [{
            type: Input
        }], close: [{
            type: Output
        }] }); })();
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassDebugInfo(MCPConnectionDialogComponent, { className: "MCPConnectionDialogComponent", filePath: "src/MCP/components/mcp-connection-dialog.component.ts", lineNumber: 33 }); })();
//# sourceMappingURL=mcp-connection-dialog.component.js.map