import * as i0 from '@angular/core';
import { signal, computed, inject, Component } from '@angular/core';
import * as i1 from '@angular/forms';
import { FormBuilder, ReactiveFormsModule } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { UserService } from '@c8y/client';
import { ContextRouteService, AlertService, Permissions, C8yTranslateDirective, LoadingComponent, BreadcrumbComponent, BreadcrumbItemComponent, C8yTranslatePipe } from '@c8y/ngx-components';
import { ApplicationAccessListComponent } from '@c8y/ngx-components/application-access/list';
import { gettext } from '@c8y/ngx-components/gettext';

class ApplicationAccessUserDetailsWrapperComponent {
    constructor() {
        this.userWithOwner = signal(null, ...(ngDevMode ? [{ debugName: "userWithOwner" }] : []));
        this.hasAppManagement = computed(() => {
            const userWithOwner = this.userWithOwner();
            if (!userWithOwner) {
                return false;
            }
            return this.hasApplicationManagementRoles(userWithOwner.user);
        }, ...(ngDevMode ? [{ debugName: "hasAppManagement" }] : []));
        this.contextService = inject(ContextRouteService);
        this.activatedRoute = inject(ActivatedRoute);
        this.userService = inject(UserService);
        this.formBuilder = inject(FormBuilder);
        this.alertService = inject(AlertService);
        this.router = inject(Router);
    }
    async ngOnInit() {
        const data = this.contextService.getContextData(this.activatedRoute);
        let user = data.contextData;
        const { data: refreshedUser } = await this.userService.detail(user.id);
        user = refreshedUser;
        let owner = null;
        if (user.owner) {
            try {
                const ownerResponse = await this.userService.detail(user.owner);
                owner = ownerResponse.data;
            }
            catch (e) {
                // proceed without owner
            }
        }
        this.userWithOwner.set({ user, owner });
        this.formGroup = this.initForm(user);
    }
    initForm(user) {
        const currentApplicationOfUser = user.applications || [];
        const form = this.formBuilder.group({
            applications: [currentApplicationOfUser]
        });
        const hasApplicationManagementRoles = this.hasApplicationManagementRoles(user);
        const isExternalUser = this.userService.isExternalUser(user);
        if (hasApplicationManagementRoles || isExternalUser) {
            form.controls.applications.disable();
        }
        if (isExternalUser) {
            this.alertService.warning(gettext('You cannot edit the user since it is managed via your authorization server.'));
        }
        return form;
    }
    async save() {
        const user = this.userWithOwner().user;
        const applications = this.formGroup.value.applications.map(app => ({
            id: app.id,
            type: app.type
        }));
        try {
            await this.userService.update({
                id: user.id,
                applications: applications
            });
            this.alertService.success(gettext("User's application access changed."));
            this.formGroup.markAsPristine();
        }
        catch (e) {
            this.alertService.danger(gettext("Failed to update user's application access."), e);
        }
    }
    cancel() {
        this.router.navigate(['users']);
    }
    ngOnDestroy() {
        // remove SSO related alert once navigating away
        this.alertService.clearAll();
    }
    hasApplicationManagementRoles(user) {
        return this.userService.hasAnyRole(user, [
            Permissions.ROLE_APPLICATION_MANAGEMENT_ADMIN,
            Permissions.ROLE_APPLICATION_MANAGEMENT_READ
        ]);
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.25", ngImport: i0, type: ApplicationAccessUserDetailsWrapperComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "20.3.25", type: ApplicationAccessUserDetailsWrapperComponent, isStandalone: true, selector: "c8y-application-access-user-details-wrapper", ngImport: i0, template: "<c8y-breadcrumb>\n  <c8y-breadcrumb-item\n    [icon]=\"'c8y-accounts'\"\n    [label]=\"'Accounts' | translate\"\n  ></c8y-breadcrumb-item>\n  <c8y-breadcrumb-item\n    [icon]=\"'c8y-accounts'\"\n    path=\"#users\"\n    [label]=\"'Users' | translate\"\n  ></c8y-breadcrumb-item>\n</c8y-breadcrumb>\n\n<div class=\"row\">\n  <div class=\"col-md-8\">\n    <div class=\"card card--fullpage\">\n      <div class=\"card-header separator\">\n        <div class=\"card-title\">\n          {{ 'Application access' | translate }}\n        </div>\n      </div>\n      <div class=\"inner-scroll\">\n        <div class=\"card-block\">\n          @if (formGroup) {\n            <form [formGroup]=\"formGroup\">\n              @if (hasAppManagement()) {\n                <div\n                  class=\"alert alert-info\"\n                  translate\n                >\n                  This user is assigned a global role with \"Application management\" permission.\n                  Therefore all applications are accessible.\n                </div>\n              }\n              <c8y-application-access-list\n                formControlName=\"applications\"\n                [userWithOwner]=\"userWithOwner()\"\n                [allSelected]=\"hasAppManagement()\"\n              ></c8y-application-access-list>\n            </form>\n          } @else {\n            <c8y-loading></c8y-loading>\n          }\n        </div>\n      </div>\n      <div class=\"card-footer separator\">\n        <button\n          class=\"btn btn-default\"\n          [title]=\"'Cancel' | translate\"\n          type=\"button\"\n          (click)=\"cancel()\"\n        >\n          {{ 'Cancel' | translate }}\n        </button>\n        <button\n          class=\"btn btn-primary\"\n          [title]=\"'Save' | translate\"\n          type=\"button\"\n          (click)=\"save()\"\n          [disabled]=\"hasAppManagement() || formGroup?.invalid || formGroup?.pristine\"\n        >\n          {{ 'Save' | translate }}\n        </button>\n      </div>\n    </div>\n  </div>\n</div>\n", dependencies: [{ kind: "directive", type: C8yTranslateDirective, selector: "[translate],[ngx-translate]" }, { kind: "component", type: ApplicationAccessListComponent, selector: "c8y-application-access-list", inputs: ["userWithOwner", "allSelected"] }, { kind: "ngmodule", type: ReactiveFormsModule }, { kind: "directive", type: i1.ɵNgNoValidate, selector: "form:not([ngNoForm]):not([ngNativeValidate])" }, { kind: "directive", type: i1.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i1.NgControlStatusGroup, selector: "[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]" }, { kind: "directive", type: i1.FormGroupDirective, selector: "[formGroup]", inputs: ["formGroup"], outputs: ["ngSubmit"], exportAs: ["ngForm"] }, { kind: "directive", type: i1.FormControlName, selector: "[formControlName]", inputs: ["formControlName", "disabled", "ngModel"], outputs: ["ngModelChange"] }, { kind: "component", type: LoadingComponent, selector: "c8y-loading", inputs: ["layout", "progress", "message"] }, { kind: "component", type: BreadcrumbComponent, selector: "c8y-breadcrumb" }, { kind: "component", type: BreadcrumbItemComponent, selector: "c8y-breadcrumb-item", inputs: ["icon", "translate", "label", "path", "injector"] }, { kind: "pipe", type: C8yTranslatePipe, name: "translate" }] }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.25", ngImport: i0, type: ApplicationAccessUserDetailsWrapperComponent, decorators: [{
            type: Component,
            args: [{ selector: 'c8y-application-access-user-details-wrapper', imports: [
                        C8yTranslatePipe,
                        C8yTranslateDirective,
                        ApplicationAccessListComponent,
                        ReactiveFormsModule,
                        LoadingComponent,
                        BreadcrumbComponent,
                        BreadcrumbItemComponent
                    ], template: "<c8y-breadcrumb>\n  <c8y-breadcrumb-item\n    [icon]=\"'c8y-accounts'\"\n    [label]=\"'Accounts' | translate\"\n  ></c8y-breadcrumb-item>\n  <c8y-breadcrumb-item\n    [icon]=\"'c8y-accounts'\"\n    path=\"#users\"\n    [label]=\"'Users' | translate\"\n  ></c8y-breadcrumb-item>\n</c8y-breadcrumb>\n\n<div class=\"row\">\n  <div class=\"col-md-8\">\n    <div class=\"card card--fullpage\">\n      <div class=\"card-header separator\">\n        <div class=\"card-title\">\n          {{ 'Application access' | translate }}\n        </div>\n      </div>\n      <div class=\"inner-scroll\">\n        <div class=\"card-block\">\n          @if (formGroup) {\n            <form [formGroup]=\"formGroup\">\n              @if (hasAppManagement()) {\n                <div\n                  class=\"alert alert-info\"\n                  translate\n                >\n                  This user is assigned a global role with \"Application management\" permission.\n                  Therefore all applications are accessible.\n                </div>\n              }\n              <c8y-application-access-list\n                formControlName=\"applications\"\n                [userWithOwner]=\"userWithOwner()\"\n                [allSelected]=\"hasAppManagement()\"\n              ></c8y-application-access-list>\n            </form>\n          } @else {\n            <c8y-loading></c8y-loading>\n          }\n        </div>\n      </div>\n      <div class=\"card-footer separator\">\n        <button\n          class=\"btn btn-default\"\n          [title]=\"'Cancel' | translate\"\n          type=\"button\"\n          (click)=\"cancel()\"\n        >\n          {{ 'Cancel' | translate }}\n        </button>\n        <button\n          class=\"btn btn-primary\"\n          [title]=\"'Save' | translate\"\n          type=\"button\"\n          (click)=\"save()\"\n          [disabled]=\"hasAppManagement() || formGroup?.invalid || formGroup?.pristine\"\n        >\n          {{ 'Save' | translate }}\n        </button>\n      </div>\n    </div>\n  </div>\n</div>\n" }]
        }] });

/**
 * Generated bundle index. Do not edit.
 */

export { ApplicationAccessUserDetailsWrapperComponent };
//# sourceMappingURL=c8y-ngx-components-application-access-user-application-access-user-details-wrapper.mjs.map
