import { Component, OnDestroy } from '@angular/core';
import { IqserPermissionsService, ListingComponent, listingProvidersFactory, LoadingService, TableColumnConfig } from '@iqser/common-ui';
import { PermissionsMapping, User } from '@red/domain';
import { ConfigService } from '../config.service';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { EntityPermissionsService } from '@services/entity-permissions/entity-permissions.service';
import { ActivatedRoute } from '@angular/router';
import { PermissionsMapService } from '@services/entity-permissions/permissions-map.service';
import { PermissionsConfigurationMapService } from '@services/entity-permissions/permissions-configuration-map.service';
import { interval, map, Subscription } from 'rxjs';
import { switchMap, tap } from 'rxjs/operators';
import { permissionsTranslations } from '@translations/permissions-translations';
import { RouterHistoryService } from '@services/router-history.service';
import { Roles } from '@users/roles';
import { getCurrentUser } from '@iqser/common-ui/lib/users';
import { SortingOrders } from '@iqser/common-ui/lib/sorting';

@Component({
    templateUrl: './permissions-screen.component.html',
    styleUrls: ['./permissions-screen.component.scss'],
    providers: listingProvidersFactory(PermissionsScreenComponent),
})
export class PermissionsScreenComponent extends ListingComponent<PermissionsMapping> implements OnDestroy {
    readonly #subscription: Subscription = new Subscription();
    readonly roles = Roles;
    readonly currentUser = getCurrentUser<User>();
    readonly translations = permissionsTranslations;
    readonly tableColumnConfigs: TableColumnConfig<PermissionsMapping>[];
    readonly tableHeaderLabel = _('permissions-screen.table-header.title');
    readonly targetObject: string;
    readonly mappedPermissions: string[];

    constructor(
        route: ActivatedRoute,
        configService: ConfigService,
        private readonly _loadingService: LoadingService,
        readonly routerHistoryService: RouterHistoryService,
        readonly permissionsService: IqserPermissionsService,
        private readonly _permissionsMapService: PermissionsMapService,
        private readonly _entityPermissionsService: EntityPermissionsService,
        permissionsConfigurationMapService: PermissionsConfigurationMapService,
    ) {
        super();
        this.targetObject = route.snapshot.data.permissionsObject;
        this.tableColumnConfigs = configService.tableConfig(this.targetObject);
        this.mappedPermissions = permissionsConfigurationMapService.getMappedPermissions(this.targetObject);
        this.sortingService.setSortingOption({
            column: 'sort',
            order: SortingOrders.asc,
        });
        this.#subscription.add(
            this._permissionsMapService
                .get$(this.targetObject)
                .pipe(
                    // force update internal mappings set in constructor
                    map(permissions => permissions.map(p => new PermissionsMapping(p))),
                    tap(permissions => this.entitiesService.setEntities(permissions)),
                )
                .subscribe(),
        );
        this.#subscription.add(
            interval(5000)
                .pipe(switchMap(() => this._entityPermissionsService.loadFor(this.targetObject)))
                .subscribe(),
        );
    }

    async togglePermission(targetPermission: string, changedPermission: string): Promise<void> {
        this._loadingService.start();
        await this._entityPermissionsService.togglePermission(this.targetObject, targetPermission, changedPermission);
        this._loadingService.stop();
    }

    ngOnDestroy(): void {
        this.#subscription.unsubscribe();
    }
}
