import {Component, Input} from '@angular/core';
import {AbstractDataFormComponent} from "@app/_components/_abstract/abstract-data-form-component";
import {
    LocationService, TripJsonld,
    TripLocationJsonld,
    TripLocationService,
} from "@app/core/api/v1";
import {AppHelperService} from "@app/_helpers/app-helper.service";
import {TranslateService} from "@ngx-translate/core";
import {Router} from "@angular/router";
import {ROUTE_BASE_DATA} from "@app/app-routing.module";
import {tripLocationForm} from "@app/_forms/apiForms";
import {ListGetDataFunctionType} from "@app/_components/list/list-get-data-function-type";
import {ListColDefinition} from "@app/_components/list/list-col-definition";
import {SearchSelectComponent} from "@app/_components/search-select/search-select.component";

@Component({
  selector: 'app-trip-location-form',
  templateUrl: './trip-location-form.component.html',
  styleUrl: './trip-location-form.component.scss'
})
export class TripLocationFormComponent extends AbstractDataFormComponent<TripLocationJsonld> {

    @Input() public trip!: TripJsonld;
    @Input() public arrivalDateTime?: string;
    @Input() public departureDateTime?: string;
    protected readonly SearchSelectComponent = SearchSelectComponent;
    protected locationColDefinitions: ListColDefinition[];

    constructor(
        private tripLocationService: TripLocationService,
        private locationService: LocationService,
        private appHelperService: AppHelperService,
        translateService: TranslateService,
        router: Router
    ) {
        super(
            tripLocationForm,
            (data: TripLocationJsonld) => {
                return this.tripLocationService.tripLocationsPost(data);
            },
            (id: string | number, data: TripLocationJsonld) =>
                this.tripLocationService.tripLocationsIdPatch(
                    id.toString(),
                    this.appHelperService.convertJsonldToJson(data)
                ),
            (id: string | number) => this.tripLocationService.tripLocationsIdDelete(id.toString()),
            translateService,
            router
        );

        this.redirectAfterDelete = '/' + ROUTE_BASE_DATA;
        this.locationColDefinitions = SearchSelectComponent.getDefaultColDefLocations();
    }

    override ngOnInit() {
        super.ngOnInit();
        this.form.get('tripIri')?.setValue(this.trip.id);
        this.form.get('arrivalDateTime')?.setValue(this.arrivalDateTime);
        this.form.get('departureDateTime')?.setValue(this.departureDateTime);
    }

    getLocations: ListGetDataFunctionType = (index: number, pageSize: number, term?: string) => {
        return this.locationService.locationsGetCollection(
            index,
            pageSize,
            term
        );
    }

    protected readonly tripLocationForm = tripLocationForm;
}
