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 { MemberService } from '../service/member.service';
import {DomainMember} from '@overflow/commons-typescript/model/domain';
import * as AuthStore from '../../shared/auth/store/auth';

@Component({
  selector: 'of-member-signin',
  templateUrl: './member-signin.component.html',
})
export class MemberSigninComponent implements OnInit {

  domainMember$: Observable<DomainMember>;
  pending$: Observable<boolean>;
  error$: Observable<any>;

  @Input() returnURL;
  @Output() resetPassword = new EventEmitter();
  @Output() signup = new EventEmitter();
  // @Output() signin = new EventEmitter<{ email: string, password: string }>();

  errorMessage: string | null;

  email: AbstractControl;
  password: AbstractControl;

  signinForm: FormGroup;

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

  ngOnInit() {
    this.initForm();
  }

  initForm() {
    this.signinForm = this.formBuilder.group({
      'email': [
        '',
        [
          Validators.required,
          Validators.email
        ]
      ],
      'password': [
        '',
        [
          Validators.required
        ]
      ],
    });
    this.email = this.signinForm.controls['email'];
    this.password = this.signinForm.controls['password'];
  }

  signinFormSubmit() {
    const formValue = Object.assign({}, this.signinForm.value);

    this.memberService.signin(formValue.email, formValue.password)
      .pipe(
        tap(() => {
          this.pending$ = of(true);
        }),
        map((r: any) => {
          this.domainMember$ = r.domainMember;
          r.returnURL = this.returnURL;
          this.store.dispatch(new AuthStore.SigninSuccess(r));
        }),
        catchError(err => {
          this.error$ = of(err);
          return of();
        }),
        tap(() => {
          this.pending$ = of(false);
        }),
        take(1),
      ).subscribe();
  }

  onResetPassword() {
    this.resetPassword.emit();
  }

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