import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { InfoService } from '../services/info.service';
import { MessageService } from '../services/message.service';

@Component({
  selector: 'app-about',
  standalone: false,
  templateUrl: './about.component.html',
  styleUrls: ['./about.component.css']
})

export class AboutComponent implements OnInit {
  messageForm: FormGroup;

  infos: Info[] = [];
  info: Info = new Info();
  commentsAll: Comment[] = [];


  comments: Comment[] = [];
  comment: Comment = new Comment();
  newComment: boolean = false;

  constructor(private fb: FormBuilder, private infoService: InfoService, private messageService: MessageService) {
    this.messageForm = this.fb.group({
      message: ['', [Validators.required, Validators.minLength(3)]],
    }); 
  }

  ngOnInit() {
    this.infos = this.infoService.getInfos();
    this.info = this.infos.length > 0 ? this.infos[this.infos.length - 1] : new Info();

    this.commentsAll = this.messageService.getMessage().slice().reverse();
    this.comment = this.commentsAll.length > 0 ? this.commentsAll[0] : new Comment();
  }

  addComment() {
    if (this.messageForm.valid) {
      const formData = this.messageForm.value;
      
      const user = this.info.gender + this.info.nameLast + ' ' + this.info.nameFirst;

      const newComment = {
        ...formData,
        user: user,
        date: new Date()
      };

      this.comments.push(newComment);
      this.messageService.addMessage(newComment);
      
      this.messageForm.reset();
    }
  }
}

export class Info {
  gender: string = 'Mister.';
  nameLast: string = 'Inconnu';
  nameFirst: string = 'PASLA';
  email: string = 'inconnu.pasla@edu.igensia.com';
  address: string = '0 rue d\'inconnu';
  codePostal: number = 1234;
}

export class Comment {
  user: string = '';
  message: string = '';
  date: Date | null = null;
}
