import {
  Component,
  OnInit,
  Output,
  EventEmitter, Input
} from '@angular/core';
import {
  FormGroup,
  FormBuilder,
  Validators,
  AbstractControl
} from '@angular/forms';
import { Store, select } from '@ngrx/store';
import { Observable, of } from 'rxjs';
import { catchError, exhaustMap, map, tap, take } from 'rxjs/operators';

import { Member } from '@overflow/commons-typescript/model/member';
import { MemberService } from '../service/member.service';

@Component({
  selector: 'of-member-reset-password',
  templateUrl: './member-reset-password.component.html',
})
export class MemberResetPasswordComponent implements OnInit {
  // @Output() resetPassword = new EventEmitter<string>();
  @Output() signin = new EventEmitter();
  @Output() signup = new EventEmitter();

  // @Input() member: Member;
  member$: Observable<Member>;
  pending$: Observable<boolean>;
  error$: Observable<any>;

  resetPasswordForm: FormGroup;
  email: AbstractControl;

  constructor(
    private store: Store<any>,
    private formBuilder: FormBuilder,
    private memberService: MemberService,
  ) {
  }

  ngOnInit() {
    this.resetPasswordForm = this.formBuilder.group({
      'email': ['', [
        Validators.required,
        Validators.email
      ]
      ]
    });

    this.email = this.resetPasswordForm.controls['email'];
  }

  resetPasswordSubmit() {
    const formValue = Object.assign({}, this.resetPasswordForm.value);
    // this.resetPassword.emit(formValue.email);
    this.memberService.sendEmailResetPassword(formValue.email)
      .pipe(
        tap(() => {
          this.pending$ = of(true);
        }),
        map((rmember: Member) => {
          this.member$ = of(rmember);
        }),
        catchError(err => {
          this.error$ = of(err);
          return of();
        }),
        tap(() => {
          this.pending$ = of(false);
        }),
        take(1),
    ).subscribe();
  }

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

  onSignup() {
    this.signup.emit();
  }

}
