import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { PageapiService } from '../../pageapi.service';
import { NbWindowService ,NbWindowRef, NB_WINDOW_CONTEXT } from '@nebular/theme';

@Component({
  selector: 'ngx-user-form',
  templateUrl: './user-form.component.html',
  styleUrls: ['./user-form.component.scss']
})
export class UserFormComponent implements OnInit {
  userForm: FormGroup | any;  formData:any =[]
  constructor(@Inject(NB_WINDOW_CONTEXT) public data: any,public _api:PageapiService,private windowService: NbWindowService, private windowRef: NbWindowRef) {

    console.log(this.data)
   }

  ngOnInit(): void {

    this.userForm = new FormGroup({

     



      role: new FormControl('', [Validators.required]),
      userName: new FormControl('', [Validators.required]),
      // contactNo: new FormControl('', [Validators.required, Validators.maxLength(20)]),
      mobileNo: new FormControl('', [Validators.required,  Validators.minLength(10),Validators.maxLength(10)]),
      // lastName: new FormControl('', [Validators.required, Validators.maxLength(20)]),
      email: new FormControl('', [Validators.required, Validators.email,Validators.pattern(
        /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,63}$/
      )]),
      // password: new FormControl('', [Validators.required, Validators.minLength(6)]),
        password: new FormControl('', [Validators.required,Validators.pattern(
          '^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*_=+-]).{8,16}$'
        )]),
      
    });
    if(this.data.hasOwnProperty('id')){
    delete this.data.password  
      this.userForm.controls['password'].clearValidators();
      this.userForm.controls['password'].updateValueAndValidity();
      }
    this.userForm.patchValue(this.data)
  }

  cancel(){
    this.windowService
    console.log( this.windowService)
    this.windowRef.close();
  }
  onSubmit(){

    console.log(this.userForm.value)
    let tmp = this.userForm.value
    this.formData =[]
    this.formData= new FormData();
    if(this.data.hasOwnProperty('id')){
      this.formData.append('id', this.data.id);
      this.formData.append('userName',tmp.userName) 
    this.formData.append('email', tmp.email);
    if(tmp.password != ""){
      this.formData.append('password', tmp.password);
    }
  
    this.formData.append('role', tmp.role);
    this.formData.append('mobileNo', tmp.mobileNo);  
    }  else{
      this.formData.append('userName',tmp.userName) 
      this.formData.append('email', tmp.email);
      this.formData.append('password', tmp.password);
      this.formData.append('role', tmp.role);
      this.formData.append('mobileNo', tmp.mobileNo);  
    }
   

    this._api.addUserFormDetails (this.formData).subscribe(res => {
      if (res.status == 200) {
console.log(res)
this.windowRef.close(1);
      }else{
        this.windowRef.close(0);
      }
    })

}
}
