import {Component, Input} from "@angular/core";
import {ActivatedRoute, Router} from "@angular/router";
import {UserService, Credentials, MessagesService} from "@webbpm/base-package";
import {CommonModule} from "@angular/common";
import {FormsModule} from "@angular/forms";

@Component({
    selector: "login",
    templateUrl: "./login.html",
    imports: [CommonModule, FormsModule]
})
export class LoginComponent {

  @Input()
  public username: string;

  @Input()
  public password: string;
  public passwordType: boolean;

  @Input()
  public errorMessage: string;

  @Input()
  public confirmationSent: boolean;

  constructor(private router: Router, private userService: UserService,
              private route: ActivatedRoute, private messagesService: MessagesService) {
  }

  ngOnInit() {
    this.confirmationSent = this.route.snapshot.queryParamMap.get('confirmationSent') === 'true';
    this.router.navigate([], { relativeTo: this.route, replaceUrl: true });
  }

  public login(): void {
    let credentials: Credentials = new Credentials();
    credentials.username = this.username;
    credentials.password = this.password;

    this.userService.login(credentials, "Password")
        .then(() => this.router.navigateByUrl("/"),
              (reason: any) => {
                switch (reason.status) {
                  case 401: {
                    this.errorMessage = $localize`:|LoginComponent.wrongCredentialsMsg:Неправильный логин или пароль`;
                    break;
                  }
                  case 404: {
                    this.errorMessage = $localize`:|LoginComponent.backendStartingPleaseWaitMsg:Приложение стартует. Пожалуйста, подождите...`;
                    break;
                  }
                  default: {
                    this.errorMessage = this.messagesService.getUnknownErrorMessage();
                    break;
                  }
                }
              }
        );
  }

  public goToRegister(): void {
    this.router.navigateByUrl("/register");
  }

  togglePasswordType(): void {
    this.passwordType = !this.passwordType;
  }
}
