import {Component, EventEmitter, Input, Output} from '@angular/core';
import {FormControl, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms';
import {Button} from 'primeng/button';
import {CommentService} from '../../services/comment.service';
import {Subscription, switchMap} from 'rxjs';
import {Comment} from '../../models/comment';
import {MessageService} from 'primeng/api';
import {NgStyle} from '@angular/common';
import {AuthService} from '../../auth.service';
import {AuthorService} from '../../services/author.service';

@Component({
  selector: 'app-comment-form',
  standalone: true,
  imports: [
    ReactiveFormsModule,
    Button,
    NgStyle
  ],
  templateUrl: './comment-form.component.html',
  styleUrl: './comment-form.component.css'
})
export class CommentFormComponent {
  commentForm = new FormGroup({
    content: new FormControl<string>('', [Validators.required, Validators.maxLength(512)]),
  });
  @Input({required: true}) postId: bigint = BigInt(1);
  @Output() commentToEmit = new EventEmitter<Comment>();
  subs: Subscription[] = [];
  createdComment: Comment = {} as Comment;

  constructor(private commentService: CommentService,
              private messageService: MessageService,
              private authService: AuthService,
              private authorService: AuthorService) {
  }

  onSubmit() {
    let token = this.authService.getAuthenticatedAuthorToken();
    let author = this.authService.getAuthenticatedAuthor();
    if (this.commentForm.valid && author && token && this.commentForm.value.content) {
      // get l'image de profile après avoir créé le commentaire
      this.subs.push(this.commentService.create(this.commentForm.value.content, this.postId, author.id, token).pipe(
        switchMap((comment: Comment) => {
          this.createdComment = { ... this.createdComment } // attention a bien mettre à jour la ref sinon ça casse
          this.createdComment.authorId = author.id;
          this.createdComment.content = comment.content;
          this.createdComment.id = comment.id;
          this.createdComment.commentDate = comment.commentDate;
          this.createdComment.authorName = author.name;
          this.createdComment.authorRole = author.role;
          this.commentForm.value.content = "";
          return this.authorService.getAvatar(author?.id)
        })
      ).subscribe({
        next: (profilePicture: string) => {
          this.createdComment.profilePicture = profilePicture;
          this.commentForm.value.content = "";
          this.commentToEmit.emit(this.createdComment);
          this.successMessage("Succès", "Commentaire créé avec succès");
        },
        error: (error) => {
          this.failureMessage("Erreur d'envois", error.error.message);
        }
      }))
    }
  }

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

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