import {
  Component,
  OnDestroy,
  OnInit,
  Output,
  EventEmitter, Input,
} from '@angular/core';
import { FormGroup, FormBuilder, Validators, AbstractControl, FormControl, ValidationErrors } from '@angular/forms';
import { Member } from '@overflow/commons-typescript/model/member';
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';

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

  member$: Observable<Member>;
  pending$: Observable<boolean>;
  error$: Observable<any>;

  signupForm: FormGroup;
  email: AbstractControl;
  password: AbstractControl;
  pwConfirm: AbstractControl;
  name: AbstractControl;
  phone: AbstractControl;
  company: AbstractControl;
  selectPolicy: AbstractControl;
  captcha: AbstractControl;
  termsDisplay = false;
  policyDisplay = false;

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


  ngOnInit() {
    this.initForm();
  }

  ngOnDestroy() {
  }

  initForm() {
    this.signupForm = this.formBuilder.group({
      'email': [
        'geekhot@hotmail.co.kr',
        [
          Validators.required,
          Validators.email
        ]
      ],
      'password': [
        '!@#$Qwer1234',
        [
          Validators.required,
          Validators.pattern('^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{6,}$'),
          Validators.minLength(6),
          Validators.maxLength(25),
        ]
      ],
      'pwConfirm': [
        '!@#$Qwer1234',
        [
          Validators.compose([
            Validators.required, this.pwMatchValidator
          ])
        ]
      ],
      'name': [
        'Park',
        [
          Validators.required,
          Validators.pattern('^[a-zA-Z 가-힣]{2,30}$')
        ]
      ],
      'phone': [
        '010-3040-0303',
        [
          Validators.required
        ]
      ],
      'company': [
        'atgame',
        [
          Validators.required
        ]
      ],
      'selectPolicy': [
        false, [Validators.requiredTrue],
      ],
      'captcha': [
        false, [Validators.requiredTrue],
      ]
    });
    this.email = this.signupForm.controls['email'];
    this.password = this.signupForm.controls['password'];
    this.pwConfirm = this.signupForm.controls['pwConfirm'];
    this.name = this.signupForm.controls['name'];
    this.phone = this.signupForm.controls['phone'];
    this.company = this.signupForm.controls['company'];
    this.selectPolicy = this.signupForm.controls['selectPolicy'];
    this.captcha = this.signupForm.controls['captcha'];
  }

  pwMatchValidator(control: FormControl): ValidationErrors {
    let pw;
    if (control.parent) {
      pw = control.parent.controls['password'].value;
    }
    if (control.value !== pw) {
      return { notMatched: true };
    }
    return null;
  }

  signupFormSubmit() {
    const signupValue = Object.assign({}, this.signupForm.value);
    const password = signupValue.password;
    const member: Member = {
      email: signupValue.email,
      name: signupValue.name,
      phone: signupValue.phone,
      companyName: signupValue.company,
    };
    this.memberService.signup(member, password)
      .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();
  }

  termsDisplayOpen() {
    this.termsDisplay = true;
  }

  policyDisplayOpen() {
    this.policyDisplay = true;
  }

  onScriptLoad() {
    console.log('Google reCAPTCHA loaded and is ready for use!');
  }

  onScriptError() {
    console.log('Something went long when loading the Google reCAPTCHA');
  }

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