import { Component, Input, Output, EventEmitter } from '@angular/core';
import { Metadata, RunView } from '@memberjunction/core';
import { MJNotificationService } from '@memberjunction/ng-notifications';
import * as i0 from "@angular/core";
import * as i1 from "@angular/forms";
import * as i2 from "@memberjunction/ng-ui-components";
function QueryCategoryDialogComponent_Conditional_0_Conditional_18_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "div", 14);
    i0.ɵɵelement(1, "i", 18);
    i0.ɵɵtext(2);
    i0.ɵɵelementEnd();
} if (rf & 2) {
    const ctx_r1 = i0.ɵɵnextContext(2);
    i0.ɵɵadvance(2);
    i0.ɵɵtextInterpolate1(" Full path: ", ctx_r1.getFullPath(), " ");
} }
function QueryCategoryDialogComponent_Conditional_0_Conditional_24_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelement(0, "i", 19);
    i0.ɵɵtext(1, " Creating... ");
} }
function QueryCategoryDialogComponent_Conditional_0_Conditional_25_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelement(0, "i", 20);
    i0.ɵɵtext(1, " Create Category ");
} }
function QueryCategoryDialogComponent_Conditional_0_Template(rf, ctx) { if (rf & 1) {
    const _r1 = i0.ɵɵgetCurrentView();
    i0.ɵɵelementStart(0, "mj-dialog", 1);
    i0.ɵɵlistener("Close", function QueryCategoryDialogComponent_Conditional_0_Template_mj_dialog_Close_0_listener() { i0.ɵɵrestoreView(_r1); const ctx_r1 = i0.ɵɵnextContext(); return i0.ɵɵresetView(ctx_r1.close()); });
    i0.ɵɵelementStart(1, "mj-dialog-titlebar")(2, "div", 2);
    i0.ɵɵelement(3, "i", 3);
    i0.ɵɵtext(4, " Create New Query Category ");
    i0.ɵɵelementEnd()();
    i0.ɵɵelementStart(5, "div", 4)(6, "div", 5)(7, "label", 6);
    i0.ɵɵelement(8, "i", 7);
    i0.ɵɵtext(9, " Category Name ");
    i0.ɵɵelementStart(10, "span", 8);
    i0.ɵɵtext(11, "*");
    i0.ɵɵelementEnd()();
    i0.ɵɵelementStart(12, "input", 9);
    i0.ɵɵtwoWayListener("ngModelChange", function QueryCategoryDialogComponent_Conditional_0_Template_input_ngModelChange_12_listener($event) { i0.ɵɵrestoreView(_r1); const ctx_r1 = i0.ɵɵnextContext(); i0.ɵɵtwoWayBindingSet(ctx_r1.categoryName, $event) || (ctx_r1.categoryName = $event); return i0.ɵɵresetView($event); });
    i0.ɵɵelementEnd()();
    i0.ɵɵelementStart(13, "div", 10)(14, "label", 11);
    i0.ɵɵelement(15, "i", 12);
    i0.ɵɵtext(16, " Parent Category (Optional) ");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(17, "mj-dropdown", 13);
    i0.ɵɵtwoWayListener("ngModelChange", function QueryCategoryDialogComponent_Conditional_0_Template_mj_dropdown_ngModelChange_17_listener($event) { i0.ɵɵrestoreView(_r1); const ctx_r1 = i0.ɵɵnextContext(); i0.ɵɵtwoWayBindingSet(ctx_r1.selectedParentId, $event) || (ctx_r1.selectedParentId = $event); return i0.ɵɵresetView($event); });
    i0.ɵɵelementEnd();
    i0.ɵɵconditionalCreate(18, QueryCategoryDialogComponent_Conditional_0_Conditional_18_Template, 3, 1, "div", 14);
    i0.ɵɵelementEnd()();
    i0.ɵɵelementStart(19, "mj-dialog-actions")(20, "button", 15);
    i0.ɵɵlistener("click", function QueryCategoryDialogComponent_Conditional_0_Template_button_click_20_listener() { i0.ɵɵrestoreView(_r1); const ctx_r1 = i0.ɵɵnextContext(); return i0.ɵɵresetView(ctx_r1.close()); });
    i0.ɵɵelement(21, "i", 16);
    i0.ɵɵtext(22, " Cancel ");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(23, "button", 17);
    i0.ɵɵlistener("click", function QueryCategoryDialogComponent_Conditional_0_Template_button_click_23_listener() { i0.ɵɵrestoreView(_r1); const ctx_r1 = i0.ɵɵnextContext(); return i0.ɵɵresetView(ctx_r1.createCategory()); });
    i0.ɵɵconditionalCreate(24, QueryCategoryDialogComponent_Conditional_0_Conditional_24_Template, 2, 0)(25, QueryCategoryDialogComponent_Conditional_0_Conditional_25_Template, 2, 0);
    i0.ɵɵelementEnd()()();
} if (rf & 2) {
    const ctx_r1 = i0.ɵɵnextContext();
    i0.ɵɵproperty("Visible", true)("Width", 500);
    i0.ɵɵadvance(12);
    i0.ɵɵtwoWayProperty("ngModel", ctx_r1.categoryName);
    i0.ɵɵadvance(5);
    i0.ɵɵtwoWayProperty("ngModel", ctx_r1.selectedParentId);
    i0.ɵɵproperty("Data", ctx_r1.flattenedCategories)("ValuePrimitive", true);
    i0.ɵɵadvance();
    i0.ɵɵconditional(ctx_r1.selectedParentId ? 18 : -1);
    i0.ɵɵadvance(5);
    i0.ɵɵproperty("disabled", !ctx_r1.categoryName.trim() || ctx_r1.isCreating);
    i0.ɵɵadvance();
    i0.ɵɵconditional(ctx_r1.isCreating ? 24 : 25);
} }
export class QueryCategoryDialogComponent {
    constructor() {
        this.isVisible = false;
        this.isVisibleChange = new EventEmitter();
        this.onCategoryCreated = new EventEmitter();
        this.categoryName = '';
        this.selectedParentId = null;
        this.categories = [];
        this.categoryTree = [];
        this.flattenedCategories = [];
        this.isCreating = false;
    }
    async ngOnInit() {
        await this.loadCategories();
    }
    async loadCategories() {
        try {
            const rv = new RunView();
            const result = await rv.RunView({
                EntityName: 'MJ: Query Categories',
                OrderBy: 'Name',
                ResultType: 'entity_object'
            });
            if (result.Success && result.Results) {
                this.categories = result.Results;
                this.categoryTree = this.buildCategoryTree(this.categories);
                this.flattenedCategories = this.flattenCategories(this.categoryTree, 0);
            }
        }
        catch (error) {
            console.error('Error loading categories:', error);
        }
    }
    buildCategoryTree(categories) {
        const categoryMap = new Map();
        const rootCategories = [];
        // Create nodes for all categories
        categories.forEach(cat => {
            categoryMap.set(cat.ID, {
                id: cat.ID,
                name: cat.Name,
                fullPath: cat.Name,
                children: [],
                level: 0
            });
        });
        // Build the tree structure
        categories.forEach(cat => {
            const node = categoryMap.get(cat.ID);
            if (cat.ParentID && categoryMap.has(cat.ParentID)) {
                const parent = categoryMap.get(cat.ParentID);
                parent.children.push(node);
                node.fullPath = `${parent.fullPath} / ${node.name}`;
            }
            else {
                rootCategories.push(node);
            }
        });
        // Sort children alphabetically
        const sortNodes = (nodes) => {
            nodes.sort((a, b) => a.name.localeCompare(b.name));
            nodes.forEach(node => sortNodes(node.children));
        };
        sortNodes(rootCategories);
        return rootCategories;
    }
    flattenCategories(nodes, level) {
        const result = [];
        nodes.forEach(node => {
            node.level = level;
            result.push(node);
            if (node.children.length > 0) {
                result.push(...this.flattenCategories(node.children, level + 1));
            }
        });
        return result;
    }
    async createCategory() {
        if (!this.categoryName.trim()) {
            MJNotificationService.Instance.CreateSimpleNotification('Please enter a category name', 'warning');
            return;
        }
        this.isCreating = true;
        try {
            const md = new Metadata();
            const newCategory = await md.GetEntityObject('MJ: Query Categories');
            newCategory.Name = this.categoryName.trim();
            newCategory.ParentID = this.selectedParentId;
            newCategory.UserID = md.CurrentUser.ID;
            const saved = await newCategory.Save();
            if (saved) {
                MJNotificationService.Instance.CreateSimpleNotification('Category created successfully', 'success');
                this.onCategoryCreated.emit(newCategory);
                this.close();
            }
            else {
                MJNotificationService.Instance.CreateSimpleNotification(`Failed to create category: ${newCategory.LatestResult?.Message || 'Unknown error'}`, 'error');
            }
        }
        catch (error) {
            console.error('Error creating category:', error);
            MJNotificationService.Instance.CreateSimpleNotification('Error creating category', 'error');
        }
        finally {
            this.isCreating = false;
        }
    }
    close() {
        this.categoryName = '';
        this.selectedParentId = null;
        this.isVisible = false;
        this.isVisibleChange.emit(false);
    }
    getCategoryIndent(category) {
        return `${category.level * 20}px`;
    }
    getFullPath() {
        const parent = this.flattenedCategories.find(c => c.id === this.selectedParentId);
        const name = this.categoryName || 'New Category';
        return parent ? `${parent.fullPath} / ${name}` : name;
    }
    static { this.ɵfac = function QueryCategoryDialogComponent_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || QueryCategoryDialogComponent)(); }; }
    static { this.ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent({ type: QueryCategoryDialogComponent, selectors: [["mj-query-category-dialog"]], inputs: { isVisible: "isVisible" }, outputs: { isVisibleChange: "isVisibleChange", onCategoryCreated: "onCategoryCreated" }, standalone: false, decls: 1, vars: 1, consts: [[3, "Visible", "Width"], [3, "Close", "Visible", "Width"], [2, "display", "flex", "align-items", "center", "gap", "8px"], [1, "fa-solid", "fa-folder-plus", 2, "color", "#28a745"], [2, "padding", "20px"], [1, "form-group", 2, "margin-bottom", "20px"], ["for", "categoryName", 2, "display", "block", "margin-bottom", "8px", "font-weight", "600", "color", "var(--mj-text-secondary)"], [1, "fa-solid", "fa-tag"], [2, "color", "#dc3545"], ["name", "categoryName", "placeholder", "Enter category name...", 1, "mj-input", 2, "width", "100%", 3, "ngModelChange", "ngModel"], [1, "form-group"], ["for", "parentCategory", 2, "display", "block", "margin-bottom", "8px", "font-weight", "600", "color", "var(--mj-text-secondary)"], [1, "fa-solid", "fa-folder-tree"], ["name", "parentCategory", "TextField", "name", "ValueField", "id", "Placeholder", "-- No Parent (Top Level) --", 2, "width", "100%", 3, "ngModelChange", "ngModel", "Data", "ValuePrimitive"], [2, "margin-top", "8px", "padding", "8px", "background", "var(--mj-bg-surface-sunken)", "border-radius", "4px", "font-size", "0.85em", "color", "var(--mj-text-muted)"], ["mjButton", "", 3, "click"], [1, "fa-solid", "fa-times"], ["mjButton", "", "variant", "primary", 3, "click", "disabled"], [1, "fa-solid", "fa-info-circle"], [1, "fa-solid", "fa-spinner", "fa-spin"], [1, "fa-solid", "fa-check"]], template: function QueryCategoryDialogComponent_Template(rf, ctx) { if (rf & 1) {
            i0.ɵɵconditionalCreate(0, QueryCategoryDialogComponent_Conditional_0_Template, 26, 9, "mj-dialog", 0);
        } if (rf & 2) {
            i0.ɵɵconditional(ctx.isVisible ? 0 : -1);
        } }, dependencies: [i1.DefaultValueAccessor, i1.NgControlStatus, i1.NgModel, i2.MJButtonDirective, i2.MJDropdownComponent, i2.MJDialogComponent, i2.MJDialogTitlebarComponent, i2.MJDialogActionsComponent], styles: ["\n\n.form-group[_ngcontent-%COMP%] {\n    margin-bottom: 20px;\n}\n\n.form-group[_ngcontent-%COMP%]   label[_ngcontent-%COMP%] {\n    display: block;\n    margin-bottom: 8px;\n    font-weight: 600;\n    color: var(--mj-text-secondary);\n}\n\n  .k-dialog {\n    border-radius: var(--mj-radius-md);\n    box-shadow: var(--mj-shadow-lg);\n}\n\n  .k-dialog-titlebar {\n    background: var(--mj-bg-surface-card);\n    border-bottom: 1px solid var(--mj-border-strong);\n    padding: 16px 20px;\n}\n\n  .k-dialog-content {\n    padding: 0;\n}"] }); }
}
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(QueryCategoryDialogComponent, [{
        type: Component,
        args: [{ standalone: false, selector: 'mj-query-category-dialog', template: "@if (isVisible) {\n  <mj-dialog\n    [Visible]=\"true\"\n    [Width]=\"500\"\n    (Close)=\"close()\">\n    <mj-dialog-titlebar>\n      <div style=\"display: flex; align-items: center; gap: 8px;\">\n        <i class=\"fa-solid fa-folder-plus\" style=\"color: #28a745;\"></i>\n        Create New Query Category\n      </div>\n    </mj-dialog-titlebar>\n    <div style=\"padding: 20px;\">\n      <div class=\"form-group\" style=\"margin-bottom: 20px;\">\n        <label for=\"categoryName\" style=\"display: block; margin-bottom: 8px; font-weight: 600; color: var(--mj-text-secondary);\">\n          <i class=\"fa-solid fa-tag\"></i> Category Name <span style=\"color: #dc3545;\">*</span>\n        </label>\n        <input class=\"mj-input\"\n          [(ngModel)]=\"categoryName\"\n          name=\"categoryName\"\n          placeholder=\"Enter category name...\"\n          style=\"width: 100%;\" />\n      </div>\n      <div class=\"form-group\">\n        <label for=\"parentCategory\" style=\"display: block; margin-bottom: 8px; font-weight: 600; color: var(--mj-text-secondary);\">\n          <i class=\"fa-solid fa-folder-tree\"></i> Parent Category (Optional)\n        </label>\n        <mj-dropdown\n          [(ngModel)]=\"selectedParentId\"\n          name=\"parentCategory\"\n          [Data]=\"flattenedCategories\"\n          TextField=\"name\"\n          ValueField=\"id\"\n          [ValuePrimitive]=\"true\"\n          Placeholder=\"-- No Parent (Top Level) --\"\n          style=\"width: 100%;\">\n        </mj-dropdown>\n        @if (selectedParentId) {\n          <div style=\"margin-top: 8px; padding: 8px; background: var(--mj-bg-surface-sunken); border-radius: 4px; font-size: 0.85em; color: var(--mj-text-muted);\">\n            <i class=\"fa-solid fa-info-circle\"></i>\n            Full path: {{ getFullPath() }}\n          </div>\n        }\n      </div>\n    </div>\n    <mj-dialog-actions>\n      <button mjButton (click)=\"close()\">\n        <i class=\"fa-solid fa-times\"></i> Cancel\n      </button>\n      <button mjButton\n        variant=\"primary\"\n        [disabled]=\"!categoryName.trim() || isCreating\"\n        (click)=\"createCategory()\">\n        @if (isCreating) {\n          <i class=\"fa-solid fa-spinner fa-spin\"></i> Creating...\n        } @else {\n          <i class=\"fa-solid fa-check\"></i> Create Category\n        }\n      </button>\n    </mj-dialog-actions>\n  </mj-dialog>\n}\n", styles: ["/* Category Dialog Styles */\n.form-group {\n    margin-bottom: 20px;\n}\n\n.form-group label {\n    display: block;\n    margin-bottom: 8px;\n    font-weight: 600;\n    color: var(--mj-text-secondary);\n}\n\n::ng-deep .k-dialog {\n    border-radius: var(--mj-radius-md);\n    box-shadow: var(--mj-shadow-lg);\n}\n\n::ng-deep .k-dialog-titlebar {\n    background: var(--mj-bg-surface-card);\n    border-bottom: 1px solid var(--mj-border-strong);\n    padding: 16px 20px;\n}\n\n::ng-deep .k-dialog-content {\n    padding: 0;\n}\n"] }]
    }], null, { isVisible: [{
            type: Input
        }], isVisibleChange: [{
            type: Output
        }], onCategoryCreated: [{
            type: Output
        }] }); })();
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassDebugInfo(QueryCategoryDialogComponent, { className: "QueryCategoryDialogComponent", filePath: "src/lib/custom/Queries/query-category-dialog.component.ts", lineNumber: 20 }); })();
//# sourceMappingURL=query-category-dialog.component.js.map