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 {Author} from '../../models/author';
import {CommentFormComponent} from '../../components/comment-form/comment-form.component';
import {Button} from 'primeng/button';
import {DialogModule} from 'primeng/dialog';
import {AuthService} from '../../auth.service';
import {Role} from '../../models/role';
import {Meta} from '@angular/platform-browser';

@Component({
  selector: 'app-post',
  standalone: true,
  imports: [
    HeaderComponent,
    DatePipe,
    AvatarModule,
    CardModule,
    SafeHtmlPipe,
    CommentFormComponent,
    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 authService: AuthService,
              private meta: Meta) {
    this.route.paramMap.subscribe(params => {
      if (!(this.authService.isSessionExpired()) && this.authService.isAuthenticated()) {
        const authenticatedAuthor = this.authService.getAuthenticatedAuthor();
        if (authenticatedAuthor) {
          this.actualAuthor = authenticatedAuthor;
        } else {
          console.error('Profil mal chargé');
        }
      } else {
        this.authService.checkSessionExpiration();
      }
      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.comments = res.comment
              this.sortCommentList()
              this.comments.forEach(comment => this.commentDeleteDialogMap.set(comment.id, false));
              this.meta.updateTag({property: 'og:title', content: res.post.title});
              this.meta.updateTag({property: 'og:description', content: this.cutDesc(res.post.description)});
              this.meta.updateTag({property: 'og:image', content: `data:image/jpeg;base64,${res.post.illustration}`});
            },
            error: err => this.failureMessage("Erreur", err.error.message)
          }));
      }
      if (this.concernedPost?.body) {
        this.concernedPost.body = this.concernedPost.body.replace(/&nbsp;/g, ' ');
      }
    });
  }

  cutDesc(desc: string): string {
    let output: string = '';
    for (let i = 0; i < 256; i++) {
      output += desc[i];
    }
    return output;
  }

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

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

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

  deleteComment(comment: Comment) {
    const token = this.authService.getAuthenticatedAuthorToken();
    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.error.message)
        })
      );
    }
  }

  sortCommentList() {
    this.comments = this.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
    });
  }

  protected readonly Role = Role;
}
