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';
import {AuthorWithPost} from '../../models/author-with-post';
import {FooterComponent} from '../../components/footer/footer.component';

@Component({
  selector: 'app-home',
  standalone: true,
  imports: [
    AvatarModule,
    HeaderComponent,
    ToastModule,
    PostHomeComponent,
    FooterComponent
  ],
  templateUrl: './home.component.html',
  styleUrl: './home.component.css'
})
export class HomeComponent implements OnDestroy {
  actualAuthor: Author | undefined;
  posts: AuthorWithPost[] = []
  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.listWithAuthors()
      .subscribe({
        next: (posts: AuthorWithPost[]) => this.posts = posts.sort((a, b) => {
          if (a.postPublicationDate > b.postPublicationDate) {
            return -1
          } else if (a.postPublicationDate < b.postPublicationDate) {
            return 1
          }
          return 0
        }),
        error: (err) => console.error(err.message),
      }));
  }

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

}
