import {
  AfterContentInit,
  AfterViewInit,
  Component,
  ElementRef,
  EventEmitter,
  Input,
  NgZone,
  OnDestroy,
  OnInit,
  Output
} from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup, FormBuilder, Validators, AbstractControl, FormControl } from '@angular/forms';
import { Member } from '@overflow/commons-typescript/model/member';
import * as AuthStore from '../../store/signup';
import {Store} from '@ngrx/store';
import { Message } from 'primeng/api';

@Component({
  selector: 'of-member-signup',
  templateUrl: './signup.component.html',
})
export class SignupComponent implements OnInit, AfterViewInit, AfterContentInit, OnDestroy {
  myRecaptcha = new FormControl(false);

  signupForm: FormGroup;
  email: AbstractControl;
  password: AbstractControl;
  pwConfirm: AbstractControl;
  name: AbstractControl;
  phone: AbstractControl;
  company: AbstractControl;
  termsDisplay = false;
  policyDisplay = false;
  msgs: Message[] = [];

  // private _instance: any = null;

  // @Input() initCallback = 'initRecaptcha';
  // @Input() siteKey = '6Ldld1gUAAAAAKBn115dpJcFpsI4G0ZTCcmP29iA';
  // @Input() theme = 'light';
  // @Input() type = 'image';
  // @Input() size = 'normal';
  // @Input() tabindex = 0;
  // @Input() language: string = null;

  // @Output() onResponse: EventEmitter<any> = new EventEmitter();
  // @Output() onExpire: EventEmitter<any> = new EventEmitter();

  constructor(
    private router: Router,
    private formBuilder: FormBuilder,
    private store: Store<AuthStore.State>,
    public el: ElementRef,
    public _zone: NgZone,
  ) { }

  ngAfterViewInit() {
    // console.log('ddddd');
  }

  ngAfterContentInit() {
    // if ((<any>window).grecaptcha) {
    //   console.log((<any>window).grecaptcha);
    //   this.init();
    // } else {
    //   (<any>window)[this.initCallback] = () => {
    //     this.init();
    //   };
    // }
  }

  init() {
    // console.log(this.el.nativeElement.children[2]);
    // console.log((<any>window).grecaptcha.render());
    //
    //
    //
    // this._instance = (<any>window).grecaptcha.render(this.el.nativeElement.children[2], {
    //   'sitekey': this.siteKey,
    //   'theme': this.theme,
    //   'type': this.type,
    //   'size': this.size,
    //   'tabindex': this.tabindex,
    //   'hl': this.language,
    //   'callback': (response: string) => {this._zone.run(() => this.recaptchaCallback(response)); },
    //   'expired-callback': () => {this._zone.run(() => this.recaptchaExpiredCallback()); },
    // });
  }

  ngOnInit() {
    this.initForm();
  }

  ngOnDestroy() {
    // if (this._instance != null) {
    //   (<any>window).grecaptcha.reset(this._instance);
    // }
  }

  reset() {
    // if (this._instance === null)
    //   return;
    //
    // (<any>window).grecaptcha.reset(this._instance);
  }

  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,
      name: signupValue.name,
      phone: signupValue.phone,
      companyName: signupValue.company,
    };
    this.store.dispatch(new AuthStore.Signup({member, password}));
    console.log(member);
  }

  termsDisplayOpen() {
    this.termsDisplay = true;
  }
  onTermsDisplayClose() {
    this.termsDisplay = false;
  }

  policyDisplayOpen() {
    this.policyDisplay = true;
  }

  onPolicyDisplayClose() {
    this.policyDisplay = false;
  }

  // showResponse(event) {
  //   this.msgs = [];
  //   this.msgs.push({severity: 'info', summary: 'Succees', detail: 'User Responded'});
  // }

  recaptchaCallback(response: string) {
    // this.onResponse.emit({
    //   response: response
    // });
  }

  recaptchaExpiredCallback() {
    // this.onExpire.emit();
  }
  onScriptLoad() {
    console.log('Google reCAPTCHA loaded and is ready for use!');
  }

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