import { Component } from '@angular/core';
import { UserJsonld, UserService } 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_USERS } from "@app/app-routing.module";
import { userForm } from "@app/_forms/apiForms";
import { AbstractImageFormComponent } from "@app/_components/_abstract/abstract-image-form-component";
import { ImageUploadService } from "@app/_services/image-upload.service";
import {Validators} from "@angular/forms";

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

    protected readonly userForm = userForm;

    override ngOnInit(): void {
        super.ngOnInit();

        // Wenn wir einen neuen Benutzer erstellen, initialisiere active mit false
        if (!this.isEditMode()) {
            this.form.get('active')?.setValue(false);
            this.form.get('isAdmin')?.setValue(false);

            // password-Feld required machen
            const passwordControl = this.form.get('password');
            if (passwordControl) {
                // Bestehende Validatoren erhalten
                const currentValidators = passwordControl.validator ? [passwordControl.validator] : [];
                // Validators.required hinzufügen
                passwordControl.setValidators([...currentValidators, Validators.required]);
                // Validatoren aktualisieren
                passwordControl.updateValueAndValidity();
            }
        }
    }

    constructor(
        private userService: UserService,
        imageUploadService: ImageUploadService,
        private appHelperService: AppHelperService,
        translateService: TranslateService,
        router: Router
    ) {
        super(
            imageUploadService,
            userForm,
            (data: UserJsonld) => userService.usersPost(data),
            (id: string | number, data: UserJsonld) =>
                userService.usersIdPatch(
                    id.toString(),
                    appHelperService.convertJsonldToJson(data)
                ),
            (id: string | number) => userService.usersIdDelete(id.toString()),
            'imageIri',
            'image.dbId',
            translateService,
            router
        );

        this.redirectAfterDelete = '/' + ROUTE_USERS;
    }
}