import {ActivatedRoute, Router, RouterModule} from "@angular/router";
import {ChangeDetectionStrategy, ChangeDetectorRef, Component} from "@angular/core";
import {Session, UserService} from "@webbpm/base-package";
import {Observable} from "rxjs";
import {AsyncPipe} from "@angular/common";
import {SharedModule} from "shared";

enum VerificationStatus {
    VERIFYING = "VERIFYING",
    VERIFIED = "VERIFIED",
    FAILED = "FAILED"
}

@Component({
    selector: "confirm",
    changeDetection: ChangeDetectionStrategy.OnPush,
    templateUrl: "./confirm-user-email.html",
    imports: [AsyncPipe, SharedModule, RouterModule]
})
export class ConfirmUserEmailComponent {
  public verificationStatus = VerificationStatus.VERIFYING;
  public currentSession: Observable<Session>;

  public errorMessage: string;

  constructor(private router: Router, private userService: UserService,
              private route: ActivatedRoute, private cd: ChangeDetectorRef) {
    this.currentSession = this.userService.getCurrentSession();
  }

  ngOnInit() {
    const link: string = this.route.snapshot.queryParamMap.get("link");
    // remove link from url to prevent http referer leakage
    this.router.navigate([], {relativeTo: this.route, replaceUrl: true});
    this.userService.confirm(
        link,
        (reason) => {
          this.verificationStatus = VerificationStatus.FAILED;
          if (reason.status === 404) {
            this.errorMessage =
                $localize`:|ConfirmUserEmailComponent.wrongConfirmEmailLink:Ссылка недействительна. Требуется повторная регистрация.`;
          }
          else {
            this.errorMessage =
                $localize`:|ConfirmUserEmailComponent.emailConfirmError:Произошла ошибка, обратитесь в службу технической поддержки!`;
          }
          this.cd.markForCheck();
        })
        .then(() => {
          this.verificationStatus = VerificationStatus.VERIFIED;
          this.cd.markForCheck();
        });
  }
}
