/**
 * @fileoverview Classify · Org-level domain-context editor.
 *
 * Reads and writes the `classify.org.context` `MJ: Application Settings` record
 * scoped to the Knowledge Hub application. This is the ORG scope of the
 * three-tier classification context (org → content-type → source) consumed by
 * the server-side `ClassificationContextResolver` during autotagging.
 *
 * Persists via `ApplicationSettingEngine.SetSetting`, which creates the record
 * if absent (or updates it) and checks the Save() result. The Knowledge Hub
 * application ID is resolved by name via the threaded provider.
 */
import { Component, ChangeDetectorRef, inject } from '@angular/core';
import { RunView } from '@memberjunction/core';
import { BaseAngularComponent } from '@memberjunction/ng-base-types';
import { MJNotificationService } from '@memberjunction/ng-notifications';
import { ApplicationSettingEngine } from '@memberjunction/core-entities';
import * as i0 from "@angular/core";
import * as i1 from "@angular/forms";
import * as i2 from "@memberjunction/ng-shared-generic";
import * as i3 from "@memberjunction/ng-ui-components";
function ClassifyOrgContextEditorComponent_ng_template_1_Conditional_3_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "span", 4);
    i0.ɵɵtext(1, "Unsaved");
    i0.ɵɵelementEnd();
} }
function ClassifyOrgContextEditorComponent_ng_template_1_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelement(0, "i", 3);
    i0.ɵɵelementStart(1, "span");
    i0.ɵɵtext(2, "Organization domain context");
    i0.ɵɵelementEnd();
    i0.ɵɵconditionalCreate(3, ClassifyOrgContextEditorComponent_ng_template_1_Conditional_3_Template, 2, 0, "span", 4);
} if (rf & 2) {
    const ctx_r0 = i0.ɵɵnextContext();
    i0.ɵɵadvance(3);
    i0.ɵɵconditional(ctx_r0.HasUnsavedChanges ? 3 : -1);
} }
function ClassifyOrgContextEditorComponent_ng_template_2_Conditional_1_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelement(0, "mj-loading", 6);
} }
function ClassifyOrgContextEditorComponent_ng_template_2_Conditional_2_Conditional_5_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelement(0, "i", 11);
    i0.ɵɵtext(1, " Saving\u2026 ");
} }
function ClassifyOrgContextEditorComponent_ng_template_2_Conditional_2_Conditional_6_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelement(0, "i", 12);
    i0.ɵɵtext(1, " Save ");
} }
function ClassifyOrgContextEditorComponent_ng_template_2_Conditional_2_Template(rf, ctx) { if (rf & 1) {
    const _r2 = i0.ɵɵgetCurrentView();
    i0.ɵɵelementStart(0, "p", 7);
    i0.ɵɵtext(1, " Applies to every source as the broadest classification-context scope. Source and content-type guidance combine with this at run time. ");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(2, "textarea", 8);
    i0.ɵɵtwoWayListener("ngModelChange", function ClassifyOrgContextEditorComponent_ng_template_2_Conditional_2_Template_textarea_ngModelChange_2_listener($event) { i0.ɵɵrestoreView(_r2); const ctx_r0 = i0.ɵɵnextContext(2); i0.ɵɵtwoWayBindingSet(ctx_r0.ContextText, $event) || (ctx_r0.ContextText = $event); return i0.ɵɵresetView($event); });
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(3, "div", 9)(4, "button", 10);
    i0.ɵɵlistener("click", function ClassifyOrgContextEditorComponent_ng_template_2_Conditional_2_Template_button_click_4_listener() { i0.ɵɵrestoreView(_r2); const ctx_r0 = i0.ɵɵnextContext(2); return i0.ɵɵresetView(ctx_r0.Save()); });
    i0.ɵɵconditionalCreate(5, ClassifyOrgContextEditorComponent_ng_template_2_Conditional_2_Conditional_5_Template, 2, 0)(6, ClassifyOrgContextEditorComponent_ng_template_2_Conditional_2_Conditional_6_Template, 2, 0);
    i0.ɵɵelementEnd()();
} if (rf & 2) {
    const ctx_r0 = i0.ɵɵnextContext(2);
    i0.ɵɵadvance(2);
    i0.ɵɵtwoWayProperty("ngModel", ctx_r0.ContextText);
    i0.ɵɵadvance(2);
    i0.ɵɵproperty("disabled", ctx_r0.IsSaving || !ctx_r0.HasUnsavedChanges);
    i0.ɵɵadvance();
    i0.ɵɵconditional(ctx_r0.IsSaving ? 5 : 6);
} }
function ClassifyOrgContextEditorComponent_ng_template_2_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "div", 5);
    i0.ɵɵconditionalCreate(1, ClassifyOrgContextEditorComponent_ng_template_2_Conditional_1_Template, 1, 0, "mj-loading", 6)(2, ClassifyOrgContextEditorComponent_ng_template_2_Conditional_2_Template, 7, 3);
    i0.ɵɵelementEnd();
} if (rf & 2) {
    const ctx_r0 = i0.ɵɵnextContext();
    i0.ɵɵadvance();
    i0.ɵɵconditional(ctx_r0.IsLoading ? 1 : 2);
} }
const KNOWLEDGE_HUB_APPLICATION_NAME = 'Knowledge Hub';
const CLASSIFY_ORG_CONTEXT_SETTING_KEY = 'classify.org.context';
export class ClassifyOrgContextEditorComponent extends BaseAngularComponent {
    cdr = inject(ChangeDetectorRef);
    /** Whether the editor body is expanded. */
    Expanded = false;
    /** The org-context text bound to the textarea. */
    ContextText = '';
    /** The value last loaded/saved, used to detect unsaved edits. */
    savedText = '';
    /** Loading spinner while reading the setting. */
    IsLoading = false;
    /** Saving spinner. */
    IsSaving = false;
    /** Whether the initial load has run. */
    loaded = false;
    khApplicationID = undefined;
    /** True when the textarea differs from the persisted value. */
    get HasUnsavedChanges() {
        return this.ContextText !== this.savedText;
    }
    /** React to the accordion expand/collapse, lazy-loading the value the first time. */
    async onExpandedChange(expanded) {
        this.Expanded = expanded;
        if (this.Expanded && !this.loaded) {
            await this.load();
        }
        this.cdr.detectChanges();
    }
    async resolveKnowledgeHubApplicationID() {
        if (this.khApplicationID !== undefined)
            return this.khApplicationID;
        const rv = RunView.FromMetadataProvider(this.ProviderToUse);
        const result = await rv.RunView({
            EntityName: 'MJ: Applications',
            ExtraFilter: `Name = '${KNOWLEDGE_HUB_APPLICATION_NAME.replace(/'/g, "''")}'`,
            Fields: ['ID'],
            MaxRows: 1,
            ResultType: 'simple',
        });
        this.khApplicationID = result.Success && result.Results.length > 0 ? result.Results[0].ID : null;
        return this.khApplicationID;
    }
    async load() {
        this.IsLoading = true;
        this.cdr.detectChanges();
        try {
            const p = this.ProviderToUse;
            await ApplicationSettingEngine.Instance.Config(false, p.CurrentUser, p);
            const appID = await this.resolveKnowledgeHubApplicationID();
            const raw = ApplicationSettingEngine.Instance.GetSetting(CLASSIFY_ORG_CONTEXT_SETTING_KEY, appID ?? undefined);
            this.ContextText = raw ?? '';
            this.savedText = this.ContextText;
            this.loaded = true;
        }
        catch (error) {
            const msg = error instanceof Error ? error.message : String(error);
            MJNotificationService.Instance.CreateSimpleNotification(`Failed to load org context: ${msg}`, 'error', 4000);
        }
        finally {
            this.IsLoading = false;
            this.cdr.detectChanges();
        }
    }
    /** Persist the org-level context to the Knowledge Hub application scope. */
    async Save() {
        if (this.IsSaving)
            return;
        this.IsSaving = true;
        this.cdr.detectChanges();
        try {
            const p = this.ProviderToUse;
            const appID = await this.resolveKnowledgeHubApplicationID();
            const ok = await ApplicationSettingEngine.Instance.SetSetting(CLASSIFY_ORG_CONTEXT_SETTING_KEY, this.ContextText, appID ?? undefined, p.CurrentUser);
            if (ok) {
                this.savedText = this.ContextText;
                MJNotificationService.Instance.CreateSimpleNotification('Org context saved', 'success', 2500);
            }
            else {
                MJNotificationService.Instance.CreateSimpleNotification('Failed to save org context', 'error', 4000);
            }
        }
        catch (error) {
            const msg = error instanceof Error ? error.message : String(error);
            MJNotificationService.Instance.CreateSimpleNotification(`Error: ${msg}`, 'error', 4000);
        }
        finally {
            this.IsSaving = false;
            this.cdr.detectChanges();
        }
    }
    static ɵfac = /*@__PURE__*/ (() => { let ɵClassifyOrgContextEditorComponent_BaseFactory; return function ClassifyOrgContextEditorComponent_Factory(__ngFactoryType__) { return (ɵClassifyOrgContextEditorComponent_BaseFactory || (ɵClassifyOrgContextEditorComponent_BaseFactory = i0.ɵɵgetInheritedFactory(ClassifyOrgContextEditorComponent)))(__ngFactoryType__ || ClassifyOrgContextEditorComponent); }; })();
    static ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent({ type: ClassifyOrgContextEditorComponent, selectors: [["classify-org-context-editor"]], standalone: false, features: [i0.ɵɵInheritDefinitionFeature], decls: 3, vars: 2, consts: [["Size", "sm", 3, "ExpandedChange", "FlushBody", "Expanded"], ["mjAccordionTitle", ""], ["mjAccordionBody", ""], [1, "fa-solid", "fa-building"], [1, "mj-accordion-badge", "mj-accordion-badge--warning", "mj-accordion-badge--right"], [1, "cls-org-ctx-body"], ["text", "Loading org context\u2026", "size", "small"], [1, "cls-org-ctx-help"], ["rows", "5", "placeholder", "Org-wide guidance for the classifier \u2014 your organization's domain, audience, taxonomy conventions\u2026", 1, "mj-textarea", 3, "ngModelChange", "ngModel"], [1, "cls-org-ctx-actions"], ["mjButton", "", "variant", "primary", "size", "sm", 3, "click", "disabled"], [1, "fa-solid", "fa-spinner", "fa-spin"], [1, "fa-solid", "fa-check"]], template: function ClassifyOrgContextEditorComponent_Template(rf, ctx) { if (rf & 1) {
            i0.ɵɵelementStart(0, "mj-accordion-panel", 0);
            i0.ɵɵlistener("ExpandedChange", function ClassifyOrgContextEditorComponent_Template_mj_accordion_panel_ExpandedChange_0_listener($event) { return ctx.onExpandedChange($event); });
            i0.ɵɵtemplate(1, ClassifyOrgContextEditorComponent_ng_template_1_Template, 4, 1, "ng-template", 1)(2, ClassifyOrgContextEditorComponent_ng_template_2_Template, 3, 1, "ng-template", 2);
            i0.ɵɵelementEnd();
        } if (rf & 2) {
            i0.ɵɵproperty("FlushBody", true)("Expanded", ctx.Expanded);
        } }, dependencies: [i1.DefaultValueAccessor, i1.NgControlStatus, i1.NgModel, i2.LoadingComponent, i3.MJButtonDirective, i3.MJAccordionPanelComponent, i3.MJAccordionTitleDirective, i3.MJAccordionBodyDirective], styles: ["\n\n\n\n.cls-org-ctx-body[_ngcontent-%COMP%] {\n    padding: 14px;\n}\n.cls-org-ctx-help[_ngcontent-%COMP%] {\n    margin: 0 0 10px;\n    font-size: 0.8rem;\n    color: var(--mj-text-muted);\n    line-height: 1.45;\n}\n.cls-org-ctx-actions[_ngcontent-%COMP%] {\n    margin-top: 10px;\n    display: flex;\n    gap: 8px;\n}"] });
}
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(ClassifyOrgContextEditorComponent, [{
        type: Component,
        args: [{ standalone: false, selector: 'classify-org-context-editor', template: "<mj-accordion-panel Size=\"sm\" [FlushBody]=\"true\" [Expanded]=\"Expanded\" (ExpandedChange)=\"onExpandedChange($event)\">\n    <ng-template mjAccordionTitle>\n        <i class=\"fa-solid fa-building\"></i>\n        <span>Organization domain context</span>\n        @if (HasUnsavedChanges) {\n            <span class=\"mj-accordion-badge mj-accordion-badge--warning mj-accordion-badge--right\">Unsaved</span>\n        }\n    </ng-template>\n    <ng-template mjAccordionBody>\n        <div class=\"cls-org-ctx-body\">\n            @if (IsLoading) {\n                <mj-loading text=\"Loading org context\u2026\" size=\"small\"></mj-loading>\n            } @else {\n                <p class=\"cls-org-ctx-help\">\n                    Applies to every source as the broadest classification-context scope. Source and\n                    content-type guidance combine with this at run time.\n                </p>\n                <textarea class=\"mj-textarea\" rows=\"5\"\n                          [(ngModel)]=\"ContextText\"\n                          placeholder=\"Org-wide guidance for the classifier \u2014 your organization's domain, audience, taxonomy conventions\u2026\"></textarea>\n                <div class=\"cls-org-ctx-actions\">\n                    <button mjButton variant=\"primary\" size=\"sm\" (click)=\"Save()\"\n                            [disabled]=\"IsSaving || !HasUnsavedChanges\">\n                        @if (IsSaving) { <i class=\"fa-solid fa-spinner fa-spin\"></i> Saving\u2026 }\n                        @else { <i class=\"fa-solid fa-check\"></i> Save }\n                    </button>\n                </div>\n            }\n        </div>\n    </ng-template>\n</mj-accordion-panel>\n", styles: ["/* cls-org-ctx wrapper + head chrome now owned by <mj-accordion-panel>.\n   Title label + \"Unsaved\" pill now use the accordion's own title layout +\n   canonical .mj-accordion-badge--warning --right \u2014 bespoke rules deleted. */\n.cls-org-ctx-body {\n    padding: 14px;\n}\n.cls-org-ctx-help {\n    margin: 0 0 10px;\n    font-size: 0.8rem;\n    color: var(--mj-text-muted);\n    line-height: 1.45;\n}\n.cls-org-ctx-actions {\n    margin-top: 10px;\n    display: flex;\n    gap: 8px;\n}\n"] }]
    }], null, null); })();
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassDebugInfo(ClassifyOrgContextEditorComponent, { className: "ClassifyOrgContextEditorComponent", filePath: "src/AI/components/autotagging/components/classify-org-context-editor.component.ts", lineNumber: 28 }); })();
//# sourceMappingURL=classify-org-context-editor.component.js.map