import { Component, Input, Output, EventEmitter } from '@angular/core';
import { AuthService } from '../services/auth.service';
import { Router } from '@angular/router';

import { FormControl, Validators } from '@angular/forms';
import { environment } from '../../environments/environment.dev';

//Compounent decleration part  here
@Component({
  selector: 'signup-component',
  templateUrl: './signup.component.html',
  styleUrls: ['./signup.component.css'],
})


// exports the class here..!
export class SignupComponent {

  @Input() email: string;
  @Input() password: string = '';
  @Input() confirm_password: string = '';
  @Input() phonenumber: any;
  @Input() firstname: string = '';
  @Input() lastname: string = '';
  @Input() institution: string = '';
  @Output() signUpSuccessRedirection = new EventEmitter<string>();
  output: string[];
  error: any;
  isError = false;
  isLoading = false;
  errorMessage = '';
  isEmailError = false;
  isPwdError = false;
  isConfirmPwdError = false;
  PwdErrMsg = '';
  comPwdErrMsg = '';
  signemailErrMsg = '';

  respData: any;
  phoneregex: RegExp = /^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[0123456789]\d{9}$/;
  emailFormControl = new FormControl('', [
    Validators.required,
    Validators.email,
  ]);
  phoneFormControl = new FormControl('', [
    Validators.required,
    Validators.pattern(this.phoneregex),
  ]);
  signupFirstStep: boolean = true;
  loginemailErrMsg = '';
  bnyregreq: boolean = false;
  userPresenceStatus: boolean;
  firstNameError = false;
  lastNameError = false;
  isPhonerror: boolean = false;
  isSuccess: boolean = false;
  firstNameErrMsg = '';
  lastNameErrMsg = '';
  phoneErrMsg = '';
  successMessage = '';
  showsignup = false;
  imgUrl = environment.imageUrl;
  constructor(private AuthService: AuthService, private router: Router) { }

  Signup() {
    var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    // var phoneregex = /^(\+\d{1,3}[- ]?)?\d{10}$/;
    let phoneregex = /^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[0123456789]\d{9}$/;
    // call AuthService function here...!

    this.isError = false;
    this.isLoading = false;
    this.isEmailError = false;
    this.isPwdError = false;
    this.isConfirmPwdError = false;

    if (this.confirm_password == this.password) {

    }
    else {
      this.isConfirmPwdError = true;
      this.comPwdErrMsg = "Password mismatched.";
    }
    if (this.confirm_password.length <= 5) {
      this.isConfirmPwdError = true;
      this.comPwdErrMsg = "Confirm Password is minimum 6 characters.";
    }
    if (this.confirm_password == null || this.confirm_password == '' || this.confirm_password == undefined) {
      this.isConfirmPwdError = true;
      this.comPwdErrMsg = "Please enter a valid confirm password .";
    }
    if (this.password.length <= 5) {
      this.isPwdError = true;
      this.PwdErrMsg = "Password is minimum 6 characters.";
    }
    if (this.password == null || this.password == '' || this.password == undefined) {
      this.isPwdError = true;
      this.PwdErrMsg = "Please enter a valid password.";
    }
    if (this.email == null || this.email == "" || this.email == undefined || !re.test(this.email)) {
      this.isEmailError = true;
      this.signemailErrMsg = "Please enter a valid email.";
    }

    let domainName = this.email.substring(this.email.lastIndexOf("@") + 1).toLowerCase();
    if (domainName === 'bnymellon.com') {
      if (this.firstname == null || this.firstname == undefined) {
        this.firstNameError = true;
        this.firstNameErrMsg = "First Name cannot be empty";
      }
      if (this.lastname == null || this.lastname == undefined) {
        this.lastNameError = true;
        this.lastNameErrMsg = "Last Name cannot be empty"
      }
      if (this.userPresenceStatus == false) {
        if (this.phonenumber == null || !phoneregex.test(this.phonenumber)) {
          this.isPhonerror = true;
          this.phoneErrMsg = "Phone/Mobile number must be of 10 digits"
        }
      }
    }
    if (domainName !== 'bnymellon.com') {
      this.isPhonerror = false;
    }
    if (!this.isEmailError && !this.isPwdError && !this.isConfirmPwdError && !this.isPhonerror) {

      this.isLoading = true;
      this.AuthService.signup({ email: this.email, password: this.password, firstName: this.firstname, lastName: this.lastname, phone: this.phonenumber, fullName: '', }).then(res => {
        // removed userName: this.email, on 15-May-2018 as per Basha.
        console.log(res)
        this.respData = res
        // console.log(this.respData)
        // console.log(this.respData.status)

        if (this.respData.status == 'error') {

          console.log(this.respData.message)
          this.isError = true;
          this.isLoading = false;
          this.error = this.respData.message
          setTimeout(() => {
            this.isError = false;
          }, 6000);
        }
        else if (this.respData.error == null) {
          this.isError = false;
          this.isLoading = false;
          this.isSuccess = true
          this.successMessage = this.respData.successMessage
          setTimeout(() => {
            this.isError = false;
            this.showsignup = false;
            //  this.showCard('login');
            this.signUpSuccessRedirection.emit('login');
            this.isSuccess = false;
            //  this.changeTab();
          }, 4000);

        }
        else {
          console.log(this.respData.error.message)
          this.isError = true;
          this.isLoading = false;
          this.error = this.respData.error.message
          setTimeout(() => {
            this.isError = false;
          }, 6000);
        }
      }).catch(err => {
        console.log(err)
        this.isError = true;
        this.isLoading = false;
        this.error = err['message']
        setTimeout(() => {
          this.isError = false;
        }, 6000);
      });
    }
  }
  suNextStep() {
    // var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    var re = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
    if (this.email == null || this.email == "" || this.email == undefined || !re.test(this.email)) {
      //alert(this.email)
      this.isEmailError = true;
      this.loginemailErrMsg = "Please provide a valid email.";
    }
    else {
      let domainName = this.email.substring(this.email.lastIndexOf("@") + 1).toLowerCase();
      if (domainName === 'bnymellon.com') {
        console.log(this.email);
        this.AuthService.checkEmailAdr(this.email).then(resp => {
          console.log("email check resp -- ", resp);
          if (resp.userPresenceStatus == true) {
            this.bnyregreq = false;
            this.signupFirstStep = false;
            this.password = '';
            this.confirm_password = '';
            this.userPresenceStatus = true;
          }
          else {
            this.bnyregreq = true;
            this.signupFirstStep = false;
            this.password = '';
            this.confirm_password = '';
          }
        })
      }
      else if (this.email == null || undefined) {

      }
      else {
        this.bnyregreq = false;
        this.signupFirstStep = false;
        this.password = '';
        this.confirm_password = '';
      }
    }
  }

  editEmailEntered() {
    this.bnyregreq = false;
    this.signupFirstStep = true;
  }

  ngOnDestroy() {
    this.signUpSuccessRedirection.unsubscribe();
  }
}

