import {Component, OnDestroy} from '@angular/core';
import {AvatarModule} from 'primeng/avatar';
import {Author} from '../../models/author';
import {Subscription} from 'rxjs';
import {HeaderComponent} from '../../components/header/header.component';
import {ToastModule} from 'primeng/toast';
import {PostService} from '../../services/post.service';
import {PostHomeComponent} from '../../components/post-home/post-home.component';
import {AuthorWithPost} from '../../models/author-with-post';
import {AuthService} from '../../auth.service';
import {LoadingComponent} from '../../components/loading/loading.component';

@Component({
  selector: 'app-home',
  standalone: true,
  imports: [
    AvatarModule,
    HeaderComponent,
    ToastModule,
    PostHomeComponent,
    LoadingComponent,
  ],
  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 authService: AuthService) {
    const authenticatedAuthor = this.authService.getAuthenticatedAuthor();
    if (!(this.authService.isSessionExpired()) && this.authService.isAuthenticated() && authenticatedAuthor) {
      this.actualAuthor = authenticatedAuthor;
    } else {
      this.authService.checkSessionExpiration();
    }
    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.error.error.message),
      }));
  }

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

}
