import { Component } from '@angular/core';
import {TripJsonld, TripService, UserJsonld, UserService, UserTripJsonld, UserTripService} from "@app/core/api/v1";
import { userTripForm } from "@app/_forms/apiForms";
import { TranslateService } from "@ngx-translate/core";
import { Router } from "@angular/router";
import { ROUTE_USER_TRIPS } from "@app/app-routing.module";
import { AppHelperService } from "@app/_helpers/app-helper.service";
import { AbstractImageFormComponent } from "@app/_components/_abstract/abstract-image-form-component";
import { ImageUploadService } from "@app/_services/image-upload.service";
import {ListColDefinition} from "@app/_components/list/list-col-definition";
import {SearchSelectComponent} from "@app/_components/search-select/search-select.component";
import {ListGetDataFunctionType} from "@app/_components/list/list-get-data-function-type";
import {of, switchMap} from "rxjs";
import {map} from "rxjs/operators";

@Component({
    selector: 'app-user-trip-form',
    templateUrl: './user-trip-form.component.html',
    styleUrl: './user-trip-form.component.scss'
})
export class UserTripFormComponent extends AbstractImageFormComponent<UserTripJsonld> {

    protected readonly userTripForm = userTripForm;
    protected userColDefinitions: ListColDefinition[];
    protected tripColDefinitions: ListColDefinition[];
    protected trip?: TripJsonld;
    protected user?: UserJsonld;

    constructor(
        protected userTripService: UserTripService,
        protected userService: UserService,
        protected tripService: TripService,
        imageUploadService: ImageUploadService,
        appHelperService: AppHelperService,
        translateService: TranslateService,
        router: Router
    ) {
        super(
            imageUploadService,
            userTripForm,
            appHelperService,
            (data: UserTripJsonld) => this.userTripService.userTripsPost(data),
            (id: string | number, data: UserTripJsonld) =>
                this.userTripService.userTripsIdPatch(
                    id.toString(),
                    this.appHelperService.convertJsonldToJson(data)
            ),
            (id: string | number) => userTripService.userTripsIdDelete(id.toString()),
            'signatureIri',
            'signature.dbId',
            translateService,
            router
        );
        this.redirectAfterDelete = '/' + ROUTE_USER_TRIPS
        this.userColDefinitions = SearchSelectComponent.getDefaultColDefUsers();
        this.tripColDefinitions = SearchSelectComponent.getDefaultColDefTrips();
    }

    override ngOnInit() {
        super.ngOnInit();

        if (this.data?.trip && !this.trip) {
            this.trip = this.data?.trip;
        }
        if (this.data?.user && !this.user) {
            this.user = this.data?.user;
        }

        if (this.trip && !this.data!.tripIri!) {
            this.data!.tripIri = this.trip.id!;
            this.form.get('tripIri')?.setValue(this.trip.id!);
        }
        if (this.user && !this.data!.userIri!) {
            this.data!.userIri = this.user.id!;
            this.form.get('userIri')?.setValue(this.user.id!);
        }
        if (!this.isEditMode()) {
            this.form.get('completed')?.setValue(false);
            this.form.get('approved')?.setValue(false);
        }
    }

    getUsers: ListGetDataFunctionType = (
        index: number,
        pageSize: number,
        term?: string,
    ) => {
        // Hole alle Benutzer mit isPilot=true
        return this.userService.usersGetCollection(
            index,
            pageSize,
            undefined,
            undefined,
            term,
            '{"isPilot":true}'
        ).pipe(
            switchMap(usersResponse => {
                // Wenn kein Trip vorhanden ist, gib alle Benutzer zurück
                if (!this.trip?.id) {
                    return of(usersResponse);
                }

                // Hole alle UserTrips für diesen Trip
                return this.userTripService.userTripsGetCollection(
                    1,
                    100,
                    this.trip.id
                ).pipe(
                    map(userTripsResponse => {
                        // Extrahiere die User-IDs aus den UserTrips
                        const usedUserIds = new Set(
                            userTripsResponse.member?.map(
                                (userTrip: UserTripJsonld) => userTrip.userIri
                            ) || []
                        );

                        // Filtere die Benutzer, die noch nicht zugeordnet sind
                        if (usersResponse.member) {
                            usersResponse.member = usersResponse.member.filter(
                                (user: UserJsonld) => !usedUserIds.has(user.id!)
                            );
                            // Aktualisiere die totalItems Anzahl
                            if (usersResponse.totalItems) {
                                usersResponse.totalItems = usersResponse.member.length;
                            }
                        }

                        return usersResponse;
                    })
                );
            })
        );
    }

    getTrips: ListGetDataFunctionType = (
        index: number,
        pageSize: number,
        term?: string,
    ) => {
        return this.tripService.tripsGetCollection(
            index,
            pageSize,
        );
    }
}