import {Component, OnDestroy} from '@angular/core';
import {HeaderComponent} from '../../components/header/header.component';
import {ActivatedRoute} from '@angular/router';
import {CookieService} from 'ngx-cookie-service';
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 {FooterComponent} from '../../components/footer/footer.component';

@Component({
  selector: 'app-profile',
  standalone: true,
  imports: [
    HeaderComponent,
    AvatarModule,
    CardModule,
    Button,
    DialogModule,
    UpdateProfileFormComponent,
    FooterComponent
  ],
  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;
  changePasswordDialog: boolean = false;

  constructor(private route: ActivatedRoute,
              private authorService: AuthorService,
              private cookieService: CookieService) {
    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.cookieService.get('author')) {
      this.actualAuthor = JSON.parse(this.cookieService.get("author"));
    }
  }

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

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

}
