import {Component} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {forkJoin, Subscription} from 'rxjs';
import {Post} from '../../models/post';
import {PostService} from '../../services/post.service';
import {HeaderComponent} from '../../components/header/header.component';
import {DatePipe} from '@angular/common';
import {CommentService} from '../../services/comment.service';
import {MessageService} from 'primeng/api';
import {Comment} from '../../models/comment';
import {AvatarModule} from 'primeng/avatar';
import {CardModule} from 'primeng/card';
import {SafeHtmlPipe} from '../../pipes/safe-html-pipe';
import {CookieService} from 'ngx-cookie-service';
import {Author} from '../../models/author';
import {CommentFormComponent} from '../../components/comment-form/comment-form.component';
import {FooterComponent} from '../../components/footer/footer.component';
import {Button} from 'primeng/button';
import {DialogModule} from 'primeng/dialog';

@Component({
  selector: 'app-post',
  standalone: true,
  imports: [
    HeaderComponent,
    DatePipe,
    AvatarModule,
    CardModule,
    SafeHtmlPipe,
    CommentFormComponent,
    FooterComponent,
    Button,
    DialogModule
  ],
  templateUrl: './post.component.html',
  styleUrl: './post.component.css'
})
export class PostComponent {
  subs: Subscription[] = [];
  comments: Comment[] = [];
  concernedPost: Post | undefined;
  actualAuthor: Author | undefined;
  commentDeleteDialogMap: Map<bigint, boolean> = new Map();


  constructor(private route: ActivatedRoute,
              private postService: PostService,
              private commentService: CommentService,
              private messageService: MessageService,
              private cookieService: CookieService,) {
    this.route.paramMap.subscribe(params => {
      if (this.cookieService.get('author')) {
        this.actualAuthor = JSON.parse(this.cookieService.get('author'))
      }
      const postId = params.get('postId');
      if (postId) {
        this.subs.push(
          forkJoin({
            post: this.postService.getPost(BigInt(postId)),
            comment: this.commentService.list(BigInt(postId))
          }).subscribe({
            next: res => {
              res.post.body = res.post.body.replace(/&nbsp;/g, ' ')
              this.concernedPost = res.post;
              this.sortCommentList(res.comment)
              this.comments = res.comment.sort((a, b) => {
                if (a.commentDate > b.commentDate) {
                  return -1
                } else if (a.commentDate < b.commentDate) {
                  return 1
                }
                return 0
              });
              this.comments.forEach(comment => this.commentDeleteDialogMap.set(comment.id, false));
            },
            error: err => this.failureMessage("Erreur", err.message)
          }));
      }
      if (this.concernedPost?.body) {
        this.concernedPost.body = this.concernedPost.body.replace(/&nbsp;/g, ' ');
      }
    });
  }

  addNewCommentToList(comment: Comment) {
    this.comments.push(comment);
    this.sortCommentList(this.comments);
  }

  setCommentDialogVisible(commentId: bigint) {
    this.commentDeleteDialogMap.set(commentId, true);
  }

  setCommentDialogHidden(commentId: bigint) {
    this.commentDeleteDialogMap.set(commentId, false);
  }

  deleteComment(comment: Comment) {
    const token = this.cookieService.get('token');
    if (token) {
      this.subs.push(
        this.commentService.delete(comment.id, token).subscribe({
          next: () => {
            this.comments = this.comments.filter(c => c.id !== comment.id);
            this.successMessage('Succès', 'Le commentaire a été supprimé avec succès');
            this.setCommentDialogHidden(comment.id);
            this.commentDeleteDialogMap.delete(comment.id);
          },
          error: err => this.failureMessage("Erreur", err.message)
        })
      );
    }
  }

  sortCommentList(comments: Comment[]) {
    comments.sort((a, b) => {
      if (a.commentDate > b.commentDate) {
        return -1
      } else if (a.commentDate < b.commentDate) {
        return 1
      }
      return 0
    })
  }

  successMessage(summary: string, detail: string): void {
    this.messageService.add({
      severity: 'success',
      summary: summary,
      detail: detail,
      life: 3000,
      closable: false
    });
  }

  failureMessage(summary: string, detail: string): void {
    this.messageService.add({
      severity: 'error',
      summary: summary,
      detail: detail,
      life: 3000,
      closable: false
    });
  }
}
