import { moveItemInArray } from '@angular/cdk/drag-drop';
import { Component, HostListener, Input } from '@angular/core';
import { AlertService, gettext } from '@c8y/ngx-components';
import { IconSelectorService } from '@c8y/ngx-components/icon-selector';
import { cloneDeep } from 'lodash-es';
import { BsModalRef } from 'ngx-bootstrap/modal';
import { BookmarkService } from '../bookmarks.service';
import * as i0 from "@angular/core";
import * as i1 from "ngx-bootstrap/modal";
import * as i2 from "@c8y/ngx-components";
import * as i3 from "../bookmarks.service";
import * as i4 from "@c8y/ngx-components/icon-selector";
import * as i5 from "@angular/common";
import * as i6 from "@angular/forms";
import * as i7 from "@angular/cdk/drag-drop";
import * as i8 from "ngx-bootstrap/tooltip";
export class EditBookmarksComponent {
    constructor(bsModalRef, alertService, bookmarkService, iconSelector) {
        this.bsModalRef = bsModalRef;
        this.alertService = alertService;
        this.bookmarkService = bookmarkService;
        this.iconSelector = iconSelector;
        this.confirmRemoveColumnButtons = [
            {
                label: gettext('Cancel'),
                action: () => Promise.resolve(false)
            },
            {
                label: gettext('Delete'),
                status: 'danger',
                action: () => Promise.resolve(true)
            }
        ];
        this.result = new Promise(resolve => {
            this._close = resolve;
        });
    }
    ngOnInit() {
        this.bookmarksToUpdate = cloneDeep(this.bookmarks);
    }
    handleKeyboardEvent(event) {
        if (event.key === 'Escape') {
            this.close();
        }
    }
    close() {
        if (this.bookmarkService.updatedBookmarks) {
            this._close(this.bookmarkService.updatedBookmarks);
        }
        this.bsModalRef.hide();
    }
    async drop(event) {
        try {
            moveItemInArray(this.bookmarks, event.previousIndex, event.currentIndex);
            moveItemInArray(this.bookmarksToUpdate, event.previousIndex, event.currentIndex);
            await this.bookmarkService.updateBookmarksInStorage(this.bookmarksToUpdate);
            this.alertService.success(gettext('Bookmarks order updated.'));
        }
        catch {
            this.alertService.success(gettext('Bookmarks order failed to update.'));
        }
    }
    async updateBookmark(updatedBookmark, type) {
        try {
            this.bookmarksToUpdate = this.updateBookmarkProperty(updatedBookmark, type);
            await this.bookmarkService.updateBookmarksInStorage(this.bookmarksToUpdate);
            if (type !== 'markToRemove') {
                this.alertService.success(gettext('Bookmark updated.'));
            }
        }
        catch {
            if (type !== 'markToRemove') {
                this.alertService.warning(gettext('Bookmark update failed'));
            }
        }
    }
    updateBookmarkProperty(updatedBookmark, type) {
        const update = {
            icon: (bookmark) => ({ ...bookmark, icon: updatedBookmark.icon }),
            label: (bookmark) => ({ ...bookmark, label: updatedBookmark.label }),
            markToRemove: (bookmark) => ({ ...bookmark, markToRemove: true })
        }[type];
        return this.bookmarksToUpdate.map(bookmark => bookmark.id === updatedBookmark.id ? update(bookmark) : bookmark);
    }
    async changeBookmarkIcon(updatedBookmark) {
        try {
            const newIcon = await this.iconSelector.selectIcon();
            updatedBookmark.icon = newIcon;
            await this.updateBookmark(updatedBookmark, 'icon');
        }
        catch {
            // nothing to do
        }
    }
    async removeBookmark(poConfirm, bookmarkToDelete) {
        poConfirm.message = gettext('This action is irreversible.');
        try {
            const remove = await poConfirm.show(this.confirmRemoveColumnButtons);
            if (!remove) {
                return;
            }
            await this.updateBookmark(bookmarkToDelete, 'markToRemove');
            const bookmarkIndex = this.bookmarks.findIndex(bookmark => bookmark.id === bookmarkToDelete.id);
            if (bookmarkIndex === -1) {
                return;
            }
            this.bookmarks.splice(bookmarkIndex, 1);
            this.alertService.success(gettext('Bookmark removed.'));
        }
        catch (err) {
            /**
             * Prevents an alert message from being displayed if the user clicks outside of a popover.
             */
            if (err) {
                this.alertService.warning(gettext('Bookmarks deletion failed.'));
            }
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.9", ngImport: i0, type: EditBookmarksComponent, deps: [{ token: i1.BsModalRef }, { token: i2.AlertService }, { token: i3.BookmarkService }, { token: i4.IconSelectorService }], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "18.2.9", type: EditBookmarksComponent, selector: "c8y-edit-bookmarks", inputs: { bookmarks: "bookmarks" }, host: { listeners: { "document:keydown": "handleKeyboardEvent($event)" } }, ngImport: i0, template: "<div class=\"viewport-modal\">\n  <div class=\"modal-header dialog-header\">\n    <i [c8yIcon]=\"'bookmark'\"></i>\n    <div\n      class=\"h4\"\n      id=\"modal-title\"\n      translate\n    >\n      Bookmarks\n    </div>\n  </div>\n  <div\n    class=\"inner-scroll\"\n    id=\"modal-body\"\n  >\n    <div class=\"p-16 text-center separator-bottom sticky-top bg-component\">\n      <p class=\"text-medium text-16\">\n        {{ 'Reorder, edit or delete bookmarks.' | translate }}\n      </p>\n    </div>\n    <c8y-list-group\n      class=\"cdk-droplist no-border-last\"\n      *ngIf=\"bookmarks.length; else emptyList\"\n      cdkDropList\n      (cdkDropListDropped)=\"drop($event)\"\n      [cdkDropListDisabled]=\"bookmarks?.length < 2\"\n    >\n      <c8y-li\n        *ngFor=\"let bookmark of bookmarks\"\n        cdkDrag\n      >\n        <c8y-li-drag-handle\n          title=\"{{ 'Drag to reorder' | translate }}\"\n          cdkDragHandle\n        >\n          <i c8yIcon=\"drag-reorder\"></i>\n        </c8y-li-drag-handle>\n        <c8y-li-icon\n          class=\"icon-24 p-relative changeIcon a-s-stretch\"\n          style=\"{{ bookmarks?.length < 2 ? 'padding-left: 16px!important' : '' }}\"\n          *ngIf=\"bookmark.icon\"\n        >\n          <i [c8yIcon]=\"bookmark.icon\"></i>\n          <button\n            class=\"btn btn-default btn-xs\"\n            [attr.aria-label]=\"'Change icon' | translate\"\n            tooltip=\"{{ 'Change icon' | translate }}\"\n            placement=\"top\"\n            container=\"body\"\n            type=\"button\"\n            [delay]=\"500\"\n            [adaptivePosition]=\"false\"\n            (click)=\"changeBookmarkIcon(bookmark)\"\n          >\n            <i c8yIcon=\"replace\"></i>\n          </button>\n        </c8y-li-icon>\n\n        <div class=\"d-flex gap-8 a-i-center\">\n          <form\n            class=\"d-flex flex-grow\"\n            name=\"bookmarksForm\"\n            #bookmarksForm=\"ngForm\"\n          >\n            <div class=\"input-group input-group-editable\">\n              <input\n                class=\"form-control fit-w\"\n                title=\"{{ bookmark.label }}\"\n                id=\"label\"\n                name=\"label\"\n                type=\"text\"\n                [(ngModel)]=\"bookmark.label\"\n                #label=\"ngModel\"\n                maxlength=\"50\"\n                [placeholder]=\"'e.g. My bookmark' | translate\"\n              />\n              <span></span>\n              <div class=\"input-group-btn\">\n                <button\n                  class=\"btn btn-primary\"\n                  title=\"{{ 'Save' | translate }}\"\n                  type=\"submit\"\n                  (click)=\"updateBookmark(bookmark, 'label'); label.control.markAsPristine()\"\n                  [disabled]=\"label.invalid\"\n                >\n                  {{ 'Save' | translate }}\n                </button>\n              </div>\n            </div>\n          </form>\n          <c8y-popover-confirm\n            class=\"d-block\"\n            [title]=\"'Delete bookmark' | translate\"\n            [placement]=\"'left'\"\n            [outsideClick]=\"true\"\n            [adaptivePosition]=\"true\"\n            [container]=\"''\"\n            #poConfirm\n          >\n            <button\n              class=\"btn btn-dot btn-dot--danger m-l-auto\"\n              title=\"{{ 'Delete' | translate }}\"\n              type=\"button\"\n              (click)=\"removeBookmark(poConfirm, bookmark)\"\n            >\n              <i c8yIcon=\"minus-circle\"></i>\n            </button>\n          </c8y-popover-confirm>\n        </div>\n      </c8y-li>\n    </c8y-list-group>\n  </div>\n  <div class=\"modal-footer\">\n    <button\n      class=\"btn btn-default\"\n      title=\"{{ 'Cancel' | translate }}\"\n      type=\"button\"\n      (click)=\"close()\"\n    >\n      {{ 'Close' | translate }}\n    </button>\n  </div>\n</div>\n<ng-template #emptyList>\n  <c8y-ui-empty-state\n    [icon]=\"'bookmark'\"\n    [title]=\"'No bookmarks yet' | translate\"\n    [subtitle]=\"\n      'Navigate to the desired page, open the right drawer and click the &quot;Add current page&quot; button.'\n        | translate\n    \"\n    [horizontal]=\"true\"\n  ></c8y-ui-empty-state>\n</ng-template>\n", dependencies: [{ kind: "component", type: i2.EmptyStateComponent, selector: "c8y-ui-empty-state", inputs: ["icon", "title", "subtitle", "horizontal"] }, { kind: "directive", type: i2.IconDirective, selector: "[c8yIcon]", inputs: ["c8yIcon"] }, { kind: "directive", type: i2.C8yTranslateDirective, selector: "[translate],[ngx-translate]" }, { kind: "directive", type: i5.NgForOf, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { kind: "directive", type: i5.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "component", type: i2.PopoverConfirmComponent, selector: "c8y-popover-confirm", inputs: ["buttons", "message", "title", "isOpen", "containerClass", "placement", "outsideClick", "adaptivePosition", "container"] }, { kind: "directive", type: i6.ɵNgNoValidate, selector: "form:not([ngNoForm]):not([ngNativeValidate])" }, { kind: "directive", type: i6.DefaultValueAccessor, selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i6.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i6.NgControlStatusGroup, selector: "[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]" }, { kind: "directive", type: i6.MaxLengthValidator, selector: "[maxlength][formControlName],[maxlength][formControl],[maxlength][ngModel]", inputs: ["maxlength"] }, { kind: "directive", type: i6.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { kind: "directive", type: i6.NgForm, selector: "form:not([ngNoForm]):not([formGroup]),ng-form,[ngForm]", inputs: ["ngFormOptions"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { kind: "component", type: i2.ListGroupComponent, selector: "c8y-list-group" }, { kind: "component", type: i2.ListItemComponent, selector: "c8y-list-item, c8y-li", inputs: ["active", "highlighted", "emptyActions", "dense", "collapsed", "selectable"], outputs: ["collapsedChange"] }, { kind: "component", type: i2.ListItemIconComponent, selector: "c8y-list-item-icon, c8y-li-icon", inputs: ["icon", "status"] }, { kind: "component", type: i2.ListItemDragHandleComponent, selector: "c8y-list-item-drag-handle, c8y-li-drag-handle" }, { kind: "directive", type: i7.CdkDropList, selector: "[cdkDropList], cdk-drop-list", inputs: ["cdkDropListConnectedTo", "cdkDropListData", "cdkDropListOrientation", "id", "cdkDropListLockAxis", "cdkDropListDisabled", "cdkDropListSortingDisabled", "cdkDropListEnterPredicate", "cdkDropListSortPredicate", "cdkDropListAutoScrollDisabled", "cdkDropListAutoScrollStep", "cdkDropListElementContainer"], outputs: ["cdkDropListDropped", "cdkDropListEntered", "cdkDropListExited", "cdkDropListSorted"], exportAs: ["cdkDropList"] }, { kind: "directive", type: i7.CdkDrag, selector: "[cdkDrag]", inputs: ["cdkDragData", "cdkDragLockAxis", "cdkDragRootElement", "cdkDragBoundary", "cdkDragStartDelay", "cdkDragFreeDragPosition", "cdkDragDisabled", "cdkDragConstrainPosition", "cdkDragPreviewClass", "cdkDragPreviewContainer", "cdkDragScale"], outputs: ["cdkDragStarted", "cdkDragReleased", "cdkDragEnded", "cdkDragEntered", "cdkDragExited", "cdkDragDropped", "cdkDragMoved"], exportAs: ["cdkDrag"] }, { kind: "directive", type: i7.CdkDragHandle, selector: "[cdkDragHandle]", inputs: ["cdkDragHandleDisabled"] }, { kind: "directive", type: i8.TooltipDirective, selector: "[tooltip], [tooltipHtml]", inputs: ["adaptivePosition", "tooltip", "placement", "triggers", "container", "containerClass", "boundariesElement", "isOpen", "isDisabled", "delay", "tooltipHtml", "tooltipPlacement", "tooltipIsOpen", "tooltipEnable", "tooltipAppendToBody", "tooltipAnimation", "tooltipClass", "tooltipContext", "tooltipPopupDelay", "tooltipFadeDuration", "tooltipTrigger"], outputs: ["tooltipChange", "onShown", "onHidden", "tooltipStateChanged"], exportAs: ["bs-tooltip"] }, { kind: "pipe", type: i2.C8yTranslatePipe, name: "translate" }] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.9", ngImport: i0, type: EditBookmarksComponent, decorators: [{
            type: Component,
            args: [{ selector: 'c8y-edit-bookmarks', template: "<div class=\"viewport-modal\">\n  <div class=\"modal-header dialog-header\">\n    <i [c8yIcon]=\"'bookmark'\"></i>\n    <div\n      class=\"h4\"\n      id=\"modal-title\"\n      translate\n    >\n      Bookmarks\n    </div>\n  </div>\n  <div\n    class=\"inner-scroll\"\n    id=\"modal-body\"\n  >\n    <div class=\"p-16 text-center separator-bottom sticky-top bg-component\">\n      <p class=\"text-medium text-16\">\n        {{ 'Reorder, edit or delete bookmarks.' | translate }}\n      </p>\n    </div>\n    <c8y-list-group\n      class=\"cdk-droplist no-border-last\"\n      *ngIf=\"bookmarks.length; else emptyList\"\n      cdkDropList\n      (cdkDropListDropped)=\"drop($event)\"\n      [cdkDropListDisabled]=\"bookmarks?.length < 2\"\n    >\n      <c8y-li\n        *ngFor=\"let bookmark of bookmarks\"\n        cdkDrag\n      >\n        <c8y-li-drag-handle\n          title=\"{{ 'Drag to reorder' | translate }}\"\n          cdkDragHandle\n        >\n          <i c8yIcon=\"drag-reorder\"></i>\n        </c8y-li-drag-handle>\n        <c8y-li-icon\n          class=\"icon-24 p-relative changeIcon a-s-stretch\"\n          style=\"{{ bookmarks?.length < 2 ? 'padding-left: 16px!important' : '' }}\"\n          *ngIf=\"bookmark.icon\"\n        >\n          <i [c8yIcon]=\"bookmark.icon\"></i>\n          <button\n            class=\"btn btn-default btn-xs\"\n            [attr.aria-label]=\"'Change icon' | translate\"\n            tooltip=\"{{ 'Change icon' | translate }}\"\n            placement=\"top\"\n            container=\"body\"\n            type=\"button\"\n            [delay]=\"500\"\n            [adaptivePosition]=\"false\"\n            (click)=\"changeBookmarkIcon(bookmark)\"\n          >\n            <i c8yIcon=\"replace\"></i>\n          </button>\n        </c8y-li-icon>\n\n        <div class=\"d-flex gap-8 a-i-center\">\n          <form\n            class=\"d-flex flex-grow\"\n            name=\"bookmarksForm\"\n            #bookmarksForm=\"ngForm\"\n          >\n            <div class=\"input-group input-group-editable\">\n              <input\n                class=\"form-control fit-w\"\n                title=\"{{ bookmark.label }}\"\n                id=\"label\"\n                name=\"label\"\n                type=\"text\"\n                [(ngModel)]=\"bookmark.label\"\n                #label=\"ngModel\"\n                maxlength=\"50\"\n                [placeholder]=\"'e.g. My bookmark' | translate\"\n              />\n              <span></span>\n              <div class=\"input-group-btn\">\n                <button\n                  class=\"btn btn-primary\"\n                  title=\"{{ 'Save' | translate }}\"\n                  type=\"submit\"\n                  (click)=\"updateBookmark(bookmark, 'label'); label.control.markAsPristine()\"\n                  [disabled]=\"label.invalid\"\n                >\n                  {{ 'Save' | translate }}\n                </button>\n              </div>\n            </div>\n          </form>\n          <c8y-popover-confirm\n            class=\"d-block\"\n            [title]=\"'Delete bookmark' | translate\"\n            [placement]=\"'left'\"\n            [outsideClick]=\"true\"\n            [adaptivePosition]=\"true\"\n            [container]=\"''\"\n            #poConfirm\n          >\n            <button\n              class=\"btn btn-dot btn-dot--danger m-l-auto\"\n              title=\"{{ 'Delete' | translate }}\"\n              type=\"button\"\n              (click)=\"removeBookmark(poConfirm, bookmark)\"\n            >\n              <i c8yIcon=\"minus-circle\"></i>\n            </button>\n          </c8y-popover-confirm>\n        </div>\n      </c8y-li>\n    </c8y-list-group>\n  </div>\n  <div class=\"modal-footer\">\n    <button\n      class=\"btn btn-default\"\n      title=\"{{ 'Cancel' | translate }}\"\n      type=\"button\"\n      (click)=\"close()\"\n    >\n      {{ 'Close' | translate }}\n    </button>\n  </div>\n</div>\n<ng-template #emptyList>\n  <c8y-ui-empty-state\n    [icon]=\"'bookmark'\"\n    [title]=\"'No bookmarks yet' | translate\"\n    [subtitle]=\"\n      'Navigate to the desired page, open the right drawer and click the &quot;Add current page&quot; button.'\n        | translate\n    \"\n    [horizontal]=\"true\"\n  ></c8y-ui-empty-state>\n</ng-template>\n" }]
        }], ctorParameters: () => [{ type: i1.BsModalRef }, { type: i2.AlertService }, { type: i3.BookmarkService }, { type: i4.IconSelectorService }], propDecorators: { bookmarks: [{
                type: Input
            }], handleKeyboardEvent: [{
                type: HostListener,
                args: ['document:keydown', ['$event']]
            }] } });
//# sourceMappingURL=data:application/json;base64, 