import {Component, Input, ViewChild} from "@angular/core";
import {AppConfigService, UserDto, UserService} from "@webbpm/base-package";
import {Router} from "@angular/router";
import {PhoneNumberComponent} from "ngx-international-phone-number";

@Component({
  moduleId: module.id,
  selector: "register",
  templateUrl: "../../../../../src/resources/template/app/component/register.html"
})
export class RegisterComponent {

  public passwordPattern: string;
  public passwordPatternErrorMessage: string;
  public errorMessage: string;

  @Input()
  public username: string;

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

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

  public fieldType: boolean;

  @Input()
  public consent: string;

  constructor(private router: Router, private userService: UserService,private appConfigService: AppConfigService) {
    this.passwordPattern = appConfigService.getParamValue("password_pattern");
    this.passwordPatternErrorMessage = appConfigService.getParamValue("password_pattern_error");
  }

  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)
        .then(() => this.router.navigateByUrl("/login?confirmationSent=true"),
              (reason: any) => {
                if (reason.status === 409) {
                  this.errorMessage = 'Пользователь с данным почтовым адресом уже существует';
                }
                else {
                  this.errorMessage = 'Произошла неизвестная ошибка, обратитесь в службу технической поддержки!';
                }
              });
  }

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

  phoneHasOnlyDialCode(): boolean {
    return this.phone.phoneNumber.trim() === this.phone.getSelectedCountryDialCode().trim()
  }

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