import {Component, Input, ViewChild} from "@angular/core";
import {AppConfigService, UserDto, UserService, MessagesService} from "@webbpm/base-package";
import {Router} from "@angular/router";
import {
  NgxIntlTelInputComponent,
  NgxIntlTelInputModule,
  SearchCountryField
} from "ngx-intl-tel-input";
import {FormsModule, NgModel} from "@angular/forms";
import {CommonModule} from "@angular/common";

@Component({
    selector: "register",
    templateUrl: "./register.html",
    imports: [CommonModule, FormsModule, NgxIntlTelInputModule]
})
export class RegisterComponent {
  SearchCountryField = SearchCountryField;
  public passwordPattern: string;
  public passwordPatternErrorMessage: string;
  public errorMessage: string;

  @Input()
  public username: string;

  @Input()
  public email: string;
  @ViewChild(NgxIntlTelInputComponent)
  public phone: NgxIntlTelInputComponent;
  public phoneNumber: string;

  public phoneIsTouched: boolean = false;
  @Input()
  public password: string;

  public fieldType: boolean;

  @Input()
  public consent: string;


  @ViewChild('phoneInput', {static: true})
  protected model: NgModel;

  constructor(private router: Router, private userService: UserService,private appConfigService: AppConfigService,
              private messagesService: MessagesService) {

    this.passwordPattern = appConfigService.getParamValue("password_pattern");
    this.passwordPatternErrorMessage =
        $localize`:|RegisterComponent.passwordPatternErrorMessage:Пароль должен содержать заглавные или прописные буквы и как минимум 1 цифру`;
  }

  public register(): void {
    let user: UserDto = new UserDto();
    user.username = this.username;
    user.email = this.email;
    user.name = this.username;
    user.phone = this.phone.value;
    user.password = this.password;

    this.userService.register(user, true)
        .then(() => this.router.navigateByUrl("/login?confirmationSent=true"))
        .catch((reason: any) => {
                if (reason.status === 409) {
                  this.errorMessage = $localize`:|NewPasswordComponent.userWithSameEmailAlreadyExists:Пользователь с данным почтовым адресом уже существует`;
                }
                else {
                  this.errorMessage = this.messagesService.getUnknownErrorMessage();
                }
              });
  }

  toggleFieldType(): void {
    this.fieldType = !this.fieldType;
  }

  phoneHasOnlyDialCode(): boolean {
    return this.phone && this.phone.phoneNumber && this.phone.selectedCountry && this.phone.phoneNumber.trim() ===
           this.phone.selectedCountry.dialCode.trim()
  }

  phoneInputFocusOut(): void {
    this.phoneIsTouched = true;
  }
}
