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

@Component({
  moduleId: module.id,
  selector: "login",
  templateUrl: "../../../../../src/resources/template/app/component/login.html"
})
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) {
  }

  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 = "Неправильный логин или пароль";
                    break;
                  }
                  case 404: {
                    this.errorMessage = "Приложение стартует. Пожалуйста, подождите...";
                    break;
                  }
                  default: {
                    this.errorMessage =
                        "Произошла неизвестная ошибка, обратитесь в службу технической поддержки!";
                    break;
                  }
                }
              }
        );
  }

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

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