import { Component, OnInit } from '@angular/core';
import {
    getConfig,
    IqserPermissionsService,
    ListingComponent,
    listingProvidersFactory,
    LoadingService,
    TableColumnConfig,
} from '@iqser/common-ui';
import { PermissionsMapping, User } from '@red/domain';
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 } 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';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';

@Component({
    templateUrl: './permissions-screen.component.html',
    styleUrls: ['./permissions-screen.component.scss'],
    providers: listingProvidersFactory(PermissionsScreenComponent),
})
export class PermissionsScreenComponent extends ListingComponent<PermissionsMapping> implements OnInit {
    readonly #config = getConfig();
    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,
        private readonly _loadingService: LoadingService,
        readonly routerHistoryService: RouterHistoryService,
        readonly permissionsService: IqserPermissionsService,
        private readonly _permissionsMapService: PermissionsMapService,
        private readonly _entityPermissionsService: EntityPermissionsService,
        private readonly _permissionsConfigurationMapService: PermissionsConfigurationMapService,
    ) {
        super();
        this.targetObject = route.snapshot.data.permissionsObject;
        this.mappedPermissions = this.getMappedPermissions(this.targetObject);
        this.tableColumnConfigs = this.getTableConfig(this.mappedPermissions);
        this.sortingService.setSortingOption({
            column: 'sort',
            order: SortingOrders.asc,
        });
        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)),
                takeUntilDestroyed(),
            )
            .subscribe();

        interval(5000)
            .pipe(
                switchMap(() => this._entityPermissionsService.loadFor(this.targetObject)),
                takeUntilDestroyed(),
            )
            .subscribe();
    }

    ngOnInit() {
        this._loadingService.stop();
    }

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

    getMappedPermissions(targetObject: string) {
        const mappedPermissions = this._permissionsConfigurationMapService.getMappedPermissions(targetObject);
        if (this.#config.IS_DOCUMINE) {
            return mappedPermissions.filter(p => p !== 'REVIEW');
        }
        return mappedPermissions;
    }

    getTableConfig(mappedPermissions: string[]) {
        const columns = mappedPermissions.map(p => ({
            label: permissionsTranslations.mapped[p],
            class: 'flex-center',
        }));

        return [{ label: _('permissions-screen.table-col-names.permission') }, ...columns];
    }
}
