import { Component } from '@angular/core';
import { KeycloakService } from 'keycloak-angular';

import { User } from '../../../../../../bizmatch-server/src/models/db.model';
import { ErrorResponse, KeycloakUser, MailInfo } from '../../../../../../bizmatch-server/src/models/main.model';
import { environment } from '../../../../environments/environment';
import { MessageService } from '../../../components/message/message.service';
import { ValidatedInputComponent } from '../../../components/validated-input/validated-input.component';
import { ValidatedTextareaComponent } from '../../../components/validated-textarea/validated-textarea.component';
import { ValidationMessagesService } from '../../../components/validation-messages.service';
import { MailService } from '../../../services/mail.service';
import { UserService } from '../../../services/user.service';
import { SharedModule } from '../../../shared/shared/shared.module';
import { map2User } from '../../../utils/utils';
@Component({
  selector: 'app-email-us',
  standalone: true,
  imports: [SharedModule, ValidatedInputComponent, ValidatedTextareaComponent],
  providers: [],
  templateUrl: './email-us.component.html',
  styleUrl: './email-us.component.scss',
})
export class EmailUsComponent {
  mailinfo: MailInfo;
  keycloakUser: KeycloakUser;
  user: User;
  errorResponse: ErrorResponse;
  constructor(
    private mailService: MailService,
    private userService: UserService,
    public keycloakService: KeycloakService,
    private validationMessagesService: ValidationMessagesService,
    private messageService: MessageService,
  ) {
    this.mailinfo = { sender: {}, email: '', url: environment.mailinfoUrl };
  }
  async ngOnInit() {
    const token = await this.keycloakService.getToken();
    this.keycloakUser = map2User(token);
    if (this.keycloakUser) {
      this.user = await this.userService.getByMail(this.keycloakUser.email);
      this.mailinfo.sender = { name: `${this.user.firstname} ${this.user.lastname}`, email: this.user.email, phoneNumber: this.user.phoneNumber, state: this.user.companyLocation.state };
    }
  }
  ngOnDestroy() {
    this.validationMessagesService.clearMessages(); // Löschen Sie alle bestehenden Validierungsnachrichten
  }
  async mail() {
    try {
      this.mailinfo.email = 'support@bizmatch.net';
      await this.mailService.mail(this.mailinfo);
      this.messageService.addMessage({ severity: 'success', text: 'Your request has been forwarded to the support team of bizmatch.', duration: 3000 });
    } catch (error) {
      this.messageService.addMessage({
        severity: 'danger',
        text: 'An error occurred',
        duration: 50000,
      });
      if (error.error && Array.isArray(error.error?.message)) {
        this.validationMessagesService.updateMessages(error.error.message);
      }
    }
  }
  containsError(fieldname: string) {
    return this.errorResponse?.fields.map(f => f.fieldname).includes(fieldname);
  }
}
