import { Component, OnInit, ViewChild } from '@angular/core';
import { FormGroup, FormControl, Validators} from '@angular/forms';
import {ResponseOptions, Response} from '@angular/http';
import {Contact} from '../contact';
import {ContactService} from '../contact.service';
import {Otp} from '../otp';
// import {Md5} from 'ts-md5/dist/md5';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { FlashMessagesService } from 'angular2-flash-messages';
import { AbstractControl, NG_VALIDATORS, Validator, ValidatorFn } from '@angular/forms';
import { NguiMessagePopupComponent, NguiPopupComponent} from '@ngui/popup';
const EMAIL_REGEX =/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;

@Component({
  selector: 'app-signup',
  templateUrl: './signup.component.html',
  styleUrls: ['./signup.component.css'],
  providers: [ContactService]
  
})
export class SignupComponent implements OnInit {
  emailFormControl = new FormControl('', [
    Validators.required,
    Validators.pattern(EMAIL_REGEX)]);
   
    public barLabel: string = "";
    @ViewChild(NguiPopupComponent) popup: NguiPopupComponent;
    first_name: string;
    last_name: string;
    email: string;
   
    password: string;
    org: string;
    phone: string;
    otp:string;
   show1:boolean = false;
   show2:boolean = true;
   show3:boolean = false;
   str:boolean = false;
    contacts: Contact[]=[];
    contact: Contact;
  Load:boolean = false;
    lname:any;
    emailId:any;
    pwd:any;
   s:any;
   wrong_Phone:any;
    org_name: string;
    OTP_Come:boolean=true;
    Enter_OTP:boolean=false;
   message: string
   login:any;
   login1:any;
   loginList:any;
   val:any;
 
    status:any;
    j:any;
    executed:any;
    executed2:any;
    mess:any;
    emmnerr:any;
    mess2:any;
    password2:any;
    dealer:boolean=false;
    constructor(private contactService: ContactService,private router: Router,private _flashMessagesService: FlashMessagesService) { }
   
    stre(){
      this.str =true;
    }
    stren(){
      this.str =false;
    }
    addContact2(){
   if(this.first_name==null || this.last_name==null || this.password==null )
     {

      this.tost1("fill_all_Rfileds")
     /*  this._flashMessagesService.show('Please fill required fields', { cssClass: 'alert-danger', timeout: 3000 }); */
      
     }
     else if(this.phone == null && this.email == null){
      this.tost1("Enter_email_mobile")
    
/*       this._flashMessagesService.show('Please fill Either Email ID or Mobile Number', { cssClass: 'alert-danger', timeout: 3000 }); */
     }
     else if(this.password2 != this.password){

      this.tost1("psd_d_cpsd")
     /*  this._flashMessagesService.show('Password and Confirm Password do not match', { cssClass: 'alert-danger', timeout: 3000 }); */

     }
     else if (this.email && this.phone){
      this.Load=true
      const newContact2 ={
      first_name: this.first_name,
      last_name: this.last_name,
      email: this.email,
      password: this.password,
      org_name: this.org,
      phone: this.phone,
      dealer: this.dealer
  }
  this.contactService.addContact(newContact2)
  .subscribe(contact => {
    this.contacts.push(contact);
    this.Load=false
    this.OTP_Come = false;
    this.Enter_OTP = true;
    window.localStorage['EmailMobile'] = 'True';
    //this.router.navigateByUrl("login");

  }, (err: any) => { 
    // console.log(err.status); 
    // console.log(err);
  if(err.status ==  500)
  {
  //  console.log(err._body);
    this.Load=false
    let r = JSON.parse(err._body);
    // console.log(r);
    if(r == '[object Object]Error: Email ID or Mobile Number Already exists'){
      this.emmnerr = r.split(":")[1];
      this.tost1("EmM")
    }
    else{
      this.emmnerr=JSON.parse(err._body);
      this.tost1("EmM")
    }
  
  }
  else{
    this.Load=false

  }
  });

}
     else if(this.phone){
   
      this.Load=true

        const newContact2 ={
        first_name: this.first_name,
        last_name: this.last_name,
        password: this.password,
        org_name: this.org,
        phone: this.phone,
        dealer: this.dealer
    }
    this.contactService.addContact(newContact2)
    .subscribe(contact => {
      this.contacts.push(contact);
      this.Load=false
      this.OTP_Come = false;
      this.Enter_OTP = true;
      this.tost1("otp_sent");
    }, (err: any) => { 
      // console.log(err.status); 
      // console.log(err);
    if(err.status ==  500)
    {
    //  console.log(err._body);
    this.Load=false
      this.wrong_Phone=JSON.parse(err._body);
      this.tost1("wrong_Phone")
    }
    else{
      this.Load=false

    }
    } );

}
else if(this.email){
  this.Load=true

  const newContact ={
      
    first_name: this.first_name,
    last_name: this.last_name,
    password: this.password,
    org_name: this.org,
    email: this.email,
    dealer: this.dealer
      }
      this.contactService.addContact(newContact)
      .subscribe(contact => {
        this.contacts.push(contact);
        if(contact.message === "Registered Sucessfully"){
          this.Load=false
        this.tost1("Confirm_Email")  
        }
      } , (err: any) => { 
     
      if(err.status ==   500)
      {
        this.Load=false
        this.dup_email = JSON.parse(err._body);
        this.tost1("dup_email")
      }
      else{
        this.Load=false

      }
      } 
    ); 
}
else{
 /*  this._flashMessagesService.show("Enter either emailid or mobile number", { cssClass: 'alert-danger', timeout: 3000 }); */
}

}
ph_data:any;
otpresend(){
  this.Load=true
  this.contactService.resendotp(this.phone).subscribe(
      
    data => {
      this.ph_data = data 
      this.Load=false
      this.tost1("otp_sent");
    });
}

cancel(){
  window.localStorage['EmailMobile'] = 'False';
  this.Load=true
  this.contactService.cancel_signup(this.phone).subscribe(
      
    data => {
      this.ph_data = data 
      this.Load=false
      this.OTP_Come = true
      this.Enter_OTP = false;
    });
 }
data_descip:any;
dup_email:any;
tost1(divid){
  if(divid == "dup_email"){
    this.data_descip = this.dup_email.message;
    launch_toast();
  }
  else if(divid == "Confirm_Email"){
    this.data_descip = "We have Send you the COnfirmation Link please check your Email ID"
    window.localStorage['Email'] = 'True'
    launch_toast();
    this.router.navigateByUrl("login");
  }
  else if(divid == "wrong_Phone"){
    this.data_descip = this.wrong_Phone.message;
    launch_toast();
  }
  else if(divid == "otp_sent")
  {
    this.data_descip = "OTP Sent Successfully";
    launch_toast();
  }
  else if(divid == "EmM"){
    this.data_descip =  this.emmnerr.message;
    launch_toast();
  }
  else if(divid == "Enter_email_mobile"){
    this.data_descip =  "Error: Enter ether mobile number or email ID"
    launch_toast();
  }
  else if(divid == "WrongOTP"){
    this.data_descip = "Error: Wrong OTP Entered"
    launch_toast();
  }
  else if(divid == "fill_all_Rfileds"){
    this.data_descip =  "Error: Please fill all required time"
    launch_toast();
  }
  else if(divid == "psd_d_cpsd"){
    this.data_descip = "Error: Password and confirm password donot match"
    launch_toast();
  }
    function launch_toast() {
     // console.log(divid);
      var x = document.getElementById("toast")
      //console.log(x);
      x.className = "show";
      setTimeout(function(){ x.className = x.className.replace("show", ""); }, 4500);
  }
   }
  







    addContact(){


  if(this.phone && this.otp){
    this.Load=true
    const newContact ={
      
            phone: this.phone,
            otp:this.otp
        }
        this.contactService.addContact(newContact)
        .subscribe(contact => {
          this.contacts.push(contact);
          // console.log(contact.message);
          if(contact.message === "Mobile Verified"){
            this.Load=false
       /*      this._flashMessagesService.show("Registered Sucessfully", { cssClass: 'success', timeout: 2000 });  */       
              if(window.localStorage.EmailMobile == 'True'){
                window.localStorage['Mobile'] = 'False'
                window.localStorage['EmailMobile'] = 'True';
                this.router.navigateByUrl("login");
              }
              else{
                window.localStorage['Mobile'] = 'True'
                this.router.navigateByUrl("login");
              }
             

          }
        } , (err: any) => {
          //  console.log(err.status); 
          // console.log(err);
        if(err.status ==   500)
        {
          this.mess = err._body.split(":")[4] ;
          this.mess2 = this.mess.split("}")[0];
          // console.log(this.mess);
          this.tost1("WrongOTP")
       /*    this._flashMessagesService.show(this.mess2 +" Wrong OTP", { cssClass: 'alert-danger', timeout: 3000 }); */
          // console.log("Error"); 
        }
        else{
          // console.log("dadsa");
        }
        } 
      ); 

  }
  else if(this.email){
    this.Load=false
    const newContact ={
      
      first_name: this.first_name,
      last_name: this.last_name,
      password: this.password,
      org_name: this.org,
      email: this.email,
      dealer: this.dealer
        }
        this.contactService.addContact(newContact)
        .subscribe(contact => {
          this.contacts.push(contact);
          // console.log(contact.message);
          if(contact.message === "Registered Sucessfully"){
       /*      this._flashMessagesService.show("Registered Sucessfully", { cssClass: 'success', timeout: 2000 });  */       
            this.router.navigateByUrl("login");
          }
        } , (err: any) => { 
      
        if(err.status ==   500)
        {
          // console.log(err._body)
       //   this.mess = err._body.split(":")[4] ;
         // this.mess2 = this.mess.split("}")[0];
        //  console.log(this.mess);
         // this._flashMessagesService.show(this.mess2 +" Wrong Values", { cssClass: 'alert-danger', timeout: 3000 });
        //  console.log("Error"); 
        }
        else{
       //   console.log("dadsa");
        }
        } 
      ); 
  }
  else{
    this.tost1("Enter_email_mobile")
  
  /*   this._flashMessagesService.show("Enter either emailid or mobile number", { cssClass: 'alert-danger', timeout: 3000 }); */ 
  }

  

    }
    valclear(){        
      
    }
 
    click1(event){
      this.show2=false;
      this.show3=true;
      if((event.keyCode >= 48 && event.keyCode <= 57) || event.keyCode == 9 || event.keyCode == 8 || event.keyCode == 46 || event.keyCode == 37 || event.keyCode == 39){
      }
      /* if(event.keyCode===13){
      this.otp_window();
      } */
      
      else
      event.preventDefault();
      }
      $event2 :any;
      click2(event2){
        this.show2=true;
        this.show3=false;
        
        }
  
       call(e) {
        {
               if (e.keyCode == 32) {
                   e.preventDefault();
               }
           }
   }

      ngOnInit() {

        this.contactService.getContacts()
        .subscribe( contacts => this.contacts = contacts);
       
        
     this.s=0;
      }
         
          
    
 
            }
