import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import * as ResetPasswordStore from '../../store/reset-password';
import {select, Store} from '@ngrx/store';
import { ResetPasswordSelector } from '../../store';
import {RPCClientError} from '@loafer/ng-rpc/protocol';
import {Member} from '@overflow/commons-typescript/model/member/index';

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

  resetPassword$ = this.resetPasswordStore.pipe(select(ResetPasswordSelector.select('member')));

  resetPassword: FormGroup;
  formErrors = {
    'email': ''
  };

  constructor(
    private resetPasswordStore: Store<ResetPasswordStore.State>,
    private router: Router,
    private formBuilder: FormBuilder) { }

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

  sendResetPassword() {
    const emailValue = Object.assign({}, this.resetPassword.value);
    console.log(emailValue.email);
    this.resetPasswordStore.dispatch(new ResetPasswordStore.ResetPassword(emailValue.email));

    const resetPasswordSubscription$ = this.resetPassword$.subscribe(
      (m: Member) => {
        if (m) {
          console.log(m);
        }

        if (resetPasswordSubscription$) {
          resetPasswordSubscription$.unsubscribe();
        }
      },
      (error: RPCClientError) => {
        console.log(error.response.message);
      }
    );
  }
}
