import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Store, select } from '@ngrx/store';

import * as AuthStore from '../../store/auth';
import { AuthSelector } from '../../store';

@Component({
  selector: 'of-member-signin',
  templateUrl: './signin.component.html',
})
export class SigninComponent implements OnInit {
  pending$ = this.store.pipe(select(AuthSelector.select('pending')));
  error$ = this.store.pipe(select(AuthSelector.select('error')));

  errorMessage: string | null;
  returnURL: string;

  signinForm: FormGroup;
  formErrors = {
    'email': '',
    'password': ''
  };

  constructor(
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private store: Store<AuthStore.State>,
    private formBuilder: FormBuilder,
  ) {
  }

  ngOnInit() {
    this.initForm();

    this.returnURL = this.activatedRoute.snapshot.queryParams['returnURL'] || '/';

    this.pending$.subscribe((pending: boolean) => {
      if (pending) {
        this.signinForm.disable();
      } else {
        this.signinForm.enable();
      }
    });

    this.error$.subscribe((error) => {
      if (error) {
        this.errorMessage = error.exception;
      } else {
        this.errorMessage = null;
      }
    });
  }

  initForm() {
    this.signinForm = this.formBuilder.group({
      'email': [
        '',
        [
          Validators.required,
          Validators.email
        ]
      ],
      'password': [
        '',
        [
          Validators.pattern('^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$'),
          Validators.minLength(6),
          Validators.maxLength(25)
        ]
      ],
    });

  }

  resetPasswordBtnClick() {
    this.router.navigateByUrl('/auth/reset-password');
  }

  signupBtnClick() {
    this.router.navigateByUrl('/auth/signup');
  }
  signin() {
    const signinValue = Object.assign({}, this.signinForm.value);
    signinValue.returnURL = this.returnURL;

    this.store.dispatch(new AuthStore.Signin(signinValue));
    console.log('signin component signin fnc');
  }

}
