import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup, FormBuilder, Validators, AbstractControl, FormControl } from '@angular/forms';
import { Member } from '../../model';
import * as AuthStore from '../../store/signup';
import {Store} from '@ngrx/store';

@Component({
  selector: 'of-member-signup',
  templateUrl: './signup.component.html',
  styleUrls: ['./signup.component.scss']
})
export class SignupComponent implements OnInit {

  signupForm: FormGroup;
  email: AbstractControl;
  password: AbstractControl;
  pwConfirm: AbstractControl;
  name: AbstractControl;
  phone: AbstractControl;
  company: AbstractControl;

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

  ngOnInit() {
    this.initForm();
  }

  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
        ]
      ],
      'phone': [
        '010-3040-0303',
        [
          Validators.required
        ]
      ],
      'company': [
        'atgame',
        [
          Validators.required
        ]
      ],
    });
    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'];
  }

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

  signup() {
    const signupValue = Object.assign({}, this.signupForm.value);
    const password = signupValue.password;
    const member: Member = {
      email: signupValue.email,
      password: signupValue.password,
      name: signupValue.name,
      phone: signupValue.phone,
      companyName: signupValue.company,
    };
    this.store.dispatch(new AuthStore.Signup({member, password}));
    console.log(member);
  }

}
