import {Component, OnDestroy} from '@angular/core';
import {AvatarModule} from 'primeng/avatar';
import {Button} from 'primeng/button';
import {AuthorService} from '../../services/author.service';
import {Author} from '../../models/author';
import {JsonPipe} from '@angular/common';
import {Subscription} from 'rxjs';
import {MessageService} from 'primeng/api';
import {HeaderComponent} from '../../components/header/header.component';
import {ToastModule} from 'primeng/toast';
import {CookieService} from 'ngx-cookie-service';
import {PostService} from '../../services/post.service';
import {Post} from '../../models/post';
import {PostHomeComponent} from '../../components/post-home/post-home.component';

@Component({
  selector: 'app-home',
  standalone: true,
  imports: [
    AvatarModule,
    HeaderComponent,
    ToastModule,
    PostHomeComponent
  ],
  templateUrl: './home.component.html',
  styleUrl: './home.component.css'
})
export class HomeComponent implements OnDestroy {
  actualAuthor: Author | undefined;
  posts: Post[] = []
  subs: Subscription[] = []

  constructor(
    private postService: PostService,
    private cookieService: CookieService) {

    if (this.cookieService.get('author')) {
      this.actualAuthor = JSON.parse(this.cookieService.get('author'));
    }
    this.subs.push(this.postService.list()
      .subscribe({
        next: (posts: Post[]) => this.posts = posts,
        error: (err) => console.error(err.message),
      }));
  }

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

}
