import { Component } from '@angular/core';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { FormBuilder, Validators } from '@angular/forms';

import { FlashMessageService } from '../../flash-message/flash-message.service';
import { Level } from '../../flash-message/level';

@Component({
  selector: 'app-contact-form',
  templateUrl: './contact-form.component.html',
  styleUrls: ['./contact-form.component.scss']
})
export class ContactFormComponent {
  public contactForm = this.$fb.group({
    name: ['', Validators.required],
    email: ['', Validators.required, Validators.email],
    subject: ['', Validators.required, Validators.maxLength(50)],
    message: [
      '',
      Validators.required,
      Validators.maxLength(600),
      Validators.minLength(15)
    ]
  });

  constructor(
    private readonly $fb: FormBuilder,
    private readonly $http: HttpClient,
    private readonly $flashMessageService: FlashMessageService
  ) {}

  public onSubmit() {
    this.$http
      .post<HttpResponse<any>>('/api/contact-form', this.contactForm.value)
      .subscribe((res: HttpResponse<any>) => {
        if (res.ok) {
          this.$flashMessageService.add(
            'Contact form submitted successfully!',
            Level.Success
          );
        } else {
          this.$flashMessageService.add(
            `Contact form failed to submit correctly. ${res.statusText}`,
            Level.Danger
          );
        }
      });
  }
}
