import {Component, OnDestroy} from '@angular/core';
import {HeaderComponent} from '../../components/header/header.component';
import {ActivatedRoute} from '@angular/router';
import {Author} from '../../models/author';
import {Subscription} from 'rxjs';
import {AuthorService} from '../../services/author.service';
import {AvatarModule} from 'primeng/avatar';
import {CardModule} from 'primeng/card';
import {Button} from 'primeng/button';
import {DialogModule} from 'primeng/dialog';
import {UpdateProfileFormComponent} from '../../components/update-profile-form/update-profile-form.component';
import {AuthService} from '../../auth.service';
import {LoadingComponent} from '../../components/loading/loading.component';

@Component({
  selector: 'app-profile',
  standalone: true,
  imports: [
    HeaderComponent,
    AvatarModule,
    CardModule,
    Button,
    DialogModule,
    UpdateProfileFormComponent,
    LoadingComponent,
  ],
  templateUrl: './profile.component.html',
  styleUrl: './profile.component.css'
})
export class ProfileComponent implements OnDestroy {
  actualAuthor: Author | undefined;
  concernedAuthor: Author | undefined;
  authorName: string = "";
  subs: Subscription[] = [];
  updateProfileDialog: boolean = false;

  constructor(private route: ActivatedRoute,
              private authorService: AuthorService,
              private authService: AuthService) {
    this.route.paramMap.subscribe(params => {
      this.subs.push(this.authorService.getAuthor(params.get('authorId')).subscribe(author => {
        this.concernedAuthor = author;
        this.authorName = author.name;
      }));
    })
    if (!(this.authService.isSessionExpired()) && this.authService.isAuthenticated()) {
      const authenticatedAuthor = this.authService.getAuthenticatedAuthor();
      if (authenticatedAuthor) {
        this.actualAuthor = authenticatedAuthor;
      } else {
        console.error("Profil mal chargé");
      }
    } else {
      this.authService.checkSessionExpiration();
    }
  }

  updateAuthor(author: Author) {
    this.concernedAuthor = author;
    this.actualAuthor = author;
  }

  ngOnDestroy(): void {
    this.subs.forEach(sub => sub.unsubscribe());
  }

}
