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

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

@Component({
  moduleId: module.id,
  selector: "confirm",
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: "../../../../../src/resources/template/app/component/confirm-user-email.html"
})
export class ConfirmUserEmailComponent {
  public verificationStatus = VerificationStatus.VERIFYING;
  public currentSession: Observable<Session>;

  @Input()
  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 = 'Ссылка недействительна. Требуется повторная регистрация.';
            }
            else {
              this.errorMessage = 'Произошла ошибка, обратитесь в службу технической поддержки!';
            }
            this.cd.markForCheck();
          })
          .then(() =>  {
              this.verificationStatus = VerificationStatus.VERIFIED;
              this.cd.markForCheck();
          });
  }
}
