import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { Observable, of } from 'rxjs';
import { catchError, exhaustMap, map, tap, take } from 'rxjs/operators';
import { FormBuilder } from '@angular/forms';
import { EmailAuthService } from '../service/email-auth.service';
import { EmailAuth } from '@overflow/commons-typescript/model/email/EmailAuth';

@Component({
  selector: 'of-member-confirm-signup',
  templateUrl: './member-confirm-signup.component.html',
})
export class MemberConfirmSignupComponent implements OnInit {
  @Input() token: string;
  @Output() signin = new EventEmitter();

  emailAuth$: Observable<EmailAuth>;
  pending$: Observable<boolean>;
  error$: Observable<any>;

  constructor(
    private store: Store<any>,
    private formBuilder: FormBuilder,
    private emailAuthService: EmailAuthService,
  ) { }
  ngOnInit(): void {
    this.emailAuthService.readBySignupAuthKey(this.token)
      .pipe(
        tap(() => {
          this.pending$ = of(true);
        }),
        map((emailAuth: EmailAuth) => {
          this.emailAuth$ = of(emailAuth);
        }),
        catchError(err => {
          this.error$ = of(err);
          return of();
        }),
        tap(() => {
          this.pending$ = of(false);
        }),
        take(1),
    ).subscribe();
  }

  onSignin() {
    this.signin.emit();
  }
}
