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/common";
import * as i2 from "@angular/forms";
import * as i3 from "@progress/kendo-angular-dialog";
import * as i4 from "@progress/kendo-angular-inputs";
import * as i5 from "@progress/kendo-angular-dropdowns";
import * as i6 from "@progress/kendo-angular-buttons";
const _c0 = () => ({ id: null, name: "-- No Parent (Top Level) --" });
function QueryCategoryDialogComponent_kendo_dialog_0_ng_template_18_Conditional_1_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelement(0, "i", 19);
} }
function QueryCategoryDialogComponent_kendo_dialog_0_ng_template_18_Conditional_2_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelement(0, "i", 20);
} }
function QueryCategoryDialogComponent_kendo_dialog_0_ng_template_18_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "div");
    i0.ɵɵtemplate(1, QueryCategoryDialogComponent_kendo_dialog_0_ng_template_18_Conditional_1_Template, 1, 0, "i", 19)(2, QueryCategoryDialogComponent_kendo_dialog_0_ng_template_18_Conditional_2_Template, 1, 0, "i", 20);
    i0.ɵɵelementStart(3, "span");
    i0.ɵɵtext(4);
    i0.ɵɵelementEnd()();
} if (rf & 2) {
    const dataItem_r3 = ctx.$implicit;
    const ctx_r1 = i0.ɵɵnextContext(2);
    i0.ɵɵstyleMapInterpolate1("padding-left: ", ctx_r1.getCategoryIndent(dataItem_r3), "; display: flex; align-items: center; gap: 6px;");
    i0.ɵɵadvance();
    i0.ɵɵconditional(dataItem_r3.children && dataItem_r3.children.length > 0 ? 1 : 2);
    i0.ɵɵadvance(3);
    i0.ɵɵtextInterpolate(dataItem_r3.name);
} }
function QueryCategoryDialogComponent_kendo_dialog_0_Conditional_19_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "div", 15);
    i0.ɵɵelement(1, "i", 21);
    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_kendo_dialog_0_Conditional_25_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelement(0, "i", 22);
    i0.ɵɵtext(1, " Creating... ");
} }
function QueryCategoryDialogComponent_kendo_dialog_0_Conditional_26_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelement(0, "i", 23);
    i0.ɵɵtext(1, " Create Category ");
} }
function QueryCategoryDialogComponent_kendo_dialog_0_Template(rf, ctx) { if (rf & 1) {
    const _r1 = i0.ɵɵgetCurrentView();
    i0.ɵɵelementStart(0, "kendo-dialog", 1);
    i0.ɵɵlistener("close", function QueryCategoryDialogComponent_kendo_dialog_0_Template_kendo_dialog_close_0_listener() { i0.ɵɵrestoreView(_r1); const ctx_r1 = i0.ɵɵnextContext(); return i0.ɵɵresetView(ctx_r1.close()); });
    i0.ɵɵelementStart(1, "kendo-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, "kendo-textbox", 9);
    i0.ɵɵtwoWayListener("ngModelChange", function QueryCategoryDialogComponent_kendo_dialog_0_Template_kendo_textbox_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, "kendo-dropdownlist", 13);
    i0.ɵɵtwoWayListener("ngModelChange", function QueryCategoryDialogComponent_kendo_dialog_0_Template_kendo_dropdownlist_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.ɵɵtemplate(18, QueryCategoryDialogComponent_kendo_dialog_0_ng_template_18_Template, 5, 5, "ng-template", 14);
    i0.ɵɵelementEnd();
    i0.ɵɵtemplate(19, QueryCategoryDialogComponent_kendo_dialog_0_Conditional_19_Template, 3, 1, "div", 15);
    i0.ɵɵelementEnd()();
    i0.ɵɵelementStart(20, "kendo-dialog-actions")(21, "button", 16);
    i0.ɵɵlistener("click", function QueryCategoryDialogComponent_kendo_dialog_0_Template_button_click_21_listener() { i0.ɵɵrestoreView(_r1); const ctx_r1 = i0.ɵɵnextContext(); return i0.ɵɵresetView(ctx_r1.close()); });
    i0.ɵɵelement(22, "i", 17);
    i0.ɵɵtext(23, " Cancel ");
    i0.ɵɵelementEnd();
    i0.ɵɵelementStart(24, "button", 18);
    i0.ɵɵlistener("click", function QueryCategoryDialogComponent_kendo_dialog_0_Template_button_click_24_listener() { i0.ɵɵrestoreView(_r1); const ctx_r1 = i0.ɵɵnextContext(); return i0.ɵɵresetView(ctx_r1.createCategory()); });
    i0.ɵɵtemplate(25, QueryCategoryDialogComponent_kendo_dialog_0_Conditional_25_Template, 2, 0)(26, QueryCategoryDialogComponent_kendo_dialog_0_Conditional_26_Template, 2, 0);
    i0.ɵɵelementEnd()()();
} if (rf & 2) {
    const ctx_r1 = i0.ɵɵnextContext();
    i0.ɵɵproperty("width", 500)("height", 400);
    i0.ɵɵadvance(12);
    i0.ɵɵtwoWayProperty("ngModel", ctx_r1.categoryName);
    i0.ɵɵadvance(5);
    i0.ɵɵtwoWayProperty("ngModel", ctx_r1.selectedParentId);
    i0.ɵɵproperty("data", ctx_r1.flattenedCategories)("textField", "name")("valueField", "id")("valuePrimitive", true)("defaultItem", i0.ɵɵpureFunction0(13, _c0));
    i0.ɵɵadvance(2);
    i0.ɵɵconditional(ctx_r1.selectedParentId ? 19 : -1);
    i0.ɵɵadvance(5);
    i0.ɵɵproperty("themeColor", "primary")("disabled", !ctx_r1.categoryName.trim() || ctx_r1.isCreating);
    i0.ɵɵadvance();
    i0.ɵɵconditional(ctx_r1.isCreating ? 25 : 26);
} }
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: '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('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(t) { return new (t || QueryCategoryDialogComponent)(); }; }
    static { this.ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent({ type: QueryCategoryDialogComponent, selectors: [["mj-query-category-dialog"]], inputs: { isVisible: "isVisible" }, outputs: { isVisibleChange: "isVisibleChange", onCategoryCreated: "onCategoryCreated" }, decls: 1, vars: 1, consts: [[3, "width", "height", "close", 4, "ngIf"], [3, "close", "width", "height"], [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", "#495057"], [1, "fa-solid", "fa-tag"], [2, "color", "#dc3545"], ["name", "categoryName", "placeholder", "Enter category name...", 2, "width", "100%", 3, "ngModelChange", "ngModel"], [1, "form-group"], ["for", "parentCategory", 2, "display", "block", "margin-bottom", "8px", "font-weight", "600", "color", "#495057"], [1, "fa-solid", "fa-folder-tree"], ["name", "parentCategory", 2, "width", "100%", 3, "ngModelChange", "ngModel", "data", "textField", "valueField", "valuePrimitive", "defaultItem"], ["kendoDropDownListItemTemplate", ""], [2, "margin-top", "8px", "padding", "8px", "background", "#f8f9fa", "border-radius", "4px", "font-size", "0.85em", "color", "#6c757d"], ["kendoButton", "", 3, "click"], [1, "fa-solid", "fa-times"], ["kendoButton", "", 3, "click", "themeColor", "disabled"], [1, "fa-solid", "fa-folder", 2, "color", "#ffc107", "font-size", "0.9em"], [1, "fa-solid", "fa-folder-open", 2, "color", "#6c757d", "font-size", "0.9em"], [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.ɵɵtemplate(0, QueryCategoryDialogComponent_kendo_dialog_0_Template, 27, 14, "kendo-dialog", 0);
        } if (rf & 2) {
            i0.ɵɵproperty("ngIf", ctx.isVisible);
        } }, dependencies: [i1.NgIf, i2.NgControlStatus, i2.NgModel, i3.DialogComponent, i3.DialogTitleBarComponent, i3.DialogActionsComponent, i4.TextBoxComponent, i5.ItemTemplateDirective, i5.DropDownListComponent, i6.ButtonComponent], 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: #495057;\n}\n\n  .k-dialog {\n    border-radius: 8px;\n    box-shadow: 0 4px 20px rgba(0,0,0,0.15);\n}\n\n  .k-dialog-titlebar {\n    background: #f8f9fa;\n    border-bottom: 1px solid #dee2e6;\n    padding: 16px 20px;\n}\n\n  .k-dialog-content {\n    padding: 0;\n}"] }); }
}
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(QueryCategoryDialogComponent, [{
        type: Component,
        args: [{ selector: 'mj-query-category-dialog', template: "<kendo-dialog \n    *ngIf=\"isVisible\"\n    [width]=\"500\"\n    [height]=\"400\"\n    (close)=\"close()\">\n    \n    <kendo-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    </kendo-dialog-titlebar>\n    \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: #495057;\">\n                <i class=\"fa-solid fa-tag\"></i> Category Name <span style=\"color: #dc3545;\">*</span>\n            </label>\n            <kendo-textbox \n                [(ngModel)]=\"categoryName\"\n                name=\"categoryName\"\n                placeholder=\"Enter category name...\"\n                style=\"width: 100%;\">\n            </kendo-textbox>\n        </div>\n        \n        <div class=\"form-group\">\n            <label for=\"parentCategory\" style=\"display: block; margin-bottom: 8px; font-weight: 600; color: #495057;\">\n                <i class=\"fa-solid fa-folder-tree\"></i> Parent Category (Optional)\n            </label>\n            <kendo-dropdownlist\n                [(ngModel)]=\"selectedParentId\"\n                name=\"parentCategory\"\n                [data]=\"flattenedCategories\"\n                [textField]=\"'name'\"\n                [valueField]=\"'id'\"\n                [valuePrimitive]=\"true\"\n                [defaultItem]=\"{id: null, name: '-- No Parent (Top Level) --'}\"\n                style=\"width: 100%;\">\n                <ng-template kendoDropDownListItemTemplate let-dataItem>\n                    <div style=\"padding-left: {{getCategoryIndent(dataItem)}}; display: flex; align-items: center; gap: 6px;\">\n                        @if (dataItem.children && dataItem.children.length > 0) {\n                            <i class=\"fa-solid fa-folder\" style=\"color: #ffc107; font-size: 0.9em;\"></i>\n                        } @else {\n                            <i class=\"fa-solid fa-folder-open\" style=\"color: #6c757d; font-size: 0.9em;\"></i>\n                        }\n                        <span>{{ dataItem.name }}</span>\n                    </div>\n                </ng-template>\n            </kendo-dropdownlist>\n            \n            @if (selectedParentId) {\n                <div style=\"margin-top: 8px; padding: 8px; background: #f8f9fa; border-radius: 4px; font-size: 0.85em; color: #6c757d;\">\n                    <i class=\"fa-solid fa-info-circle\"></i>\n                    Full path: {{ getFullPath() }}\n                </div>\n            }\n        </div>\n    </div>\n    \n    <kendo-dialog-actions>\n        <button kendoButton (click)=\"close()\">\n            <i class=\"fa-solid fa-times\"></i> Cancel\n        </button>\n        <button kendoButton \n                [themeColor]=\"'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    </kendo-dialog-actions>\n</kendo-dialog>", 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: #495057;\n}\n\n::ng-deep .k-dialog {\n    border-radius: 8px;\n    box-shadow: 0 4px 20px rgba(0,0,0,0.15);\n}\n\n::ng-deep .k-dialog-titlebar {\n    background: #f8f9fa;\n    border-bottom: 1px solid #dee2e6;\n    padding: 16px 20px;\n}\n\n::ng-deep .k-dialog-content {\n    padding: 0;\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: 19 }); })();
//# sourceMappingURL=query-category-dialog.component.js.map