import {AfterViewInit, Component, Input, OnInit, ViewChild} from '@angular/core';
import {UserJsonld, UserService} from "@app/core/api/v1";
import {AccountService} from "@app/_services";
import {AppHelperService} from "@app/_helpers/app-helper.service";
import {ActivatedRoute} from "@angular/router";
import {FormMode, FormSubmitEvent} from "@app/_components/_abstract/abstract-data-form-component";
import {ModalStatus} from "@app/_helpers/modal.states";

@Component({
    selector: 'app-user-detail',
    templateUrl: './user-detail.component.html',
    styleUrl: './user-detail.component.scss'
})
export class UserDetailComponent implements OnInit, AfterViewInit {
    @Input() public user!: UserJsonld;
    protected readonly FormMode = FormMode;

    protected isCurrentUser: boolean;

    constructor(
        private accountService: AccountService,
        private userService: UserService,
        protected appHelperService: AppHelperService,
        private route: ActivatedRoute,
    ) {
        this.isCurrentUser = false;
    }

    ngOnInit() {
        if (this.user === undefined) {
            this.route.params.subscribe(params => {
                this.getUserData(params['id']);
            });
        } else {
            this.setIsCurrentUser();
        }
    }

    ngAfterViewInit(): void {

    }

    getUserData(userId: string) {
        this.userService.usersIdGet(
            userId
        ).subscribe(
            data => {
                this.user = data;
                this.setIsCurrentUser();
            }
        );
    }

    setIsCurrentUser() {
        if (this.accountService.userValue) {
            let user = this.accountService.userValue;
            this.isCurrentUser = this.appHelperService.extractId(this.user.id) == user?.id;
        }
    }

    onFormUpdate(event: FormSubmitEvent<UserJsonld>) {
        if (event.status === ModalStatus.Submitted && event.data) {
            this.user = event.data;
        }
    }
}
