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';
import { map } from 'rxjs/internal/operators/map';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../../../environments/environment.prod';

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

    console.log(this.data)
    this.action = this.data.action;
    console.log(this.action)
   }

  ngOnInit(): void {
    let valData =  [this.validateUsernameAvailability.bind(this)]
     
    this.userForm = new FormGroup({ 
      productCategory: new FormControl('', [Validators.required]),
      productType: new FormControl('', [Validators.required]),
      productName: new FormControl('', [Validators.required]),
      description:new FormControl('', [Validators.required]),
      skuId:new FormControl('', [Validators.required],valData),
      
    });
    if(this.data.hasOwnProperty('id')){
      // this.userForm.controls['password'].clearValidators();
      // this.userForm.controls['password'].updateValueAndValidity();
      }
    this.userForm.patchValue(this.data)
  }
  
  validateUsernameAvailability(control: FormControl) {      
    let param ={}
    return this.http.post<any[]>(this.apiUrl+ "getProducts",param)
      .pipe(
        map((response:any) => {
          console.log('edit',response)
          let productData
          if(this.action == 'Add'){
            console.log('add')
            productData = response.data
          }else{
            console.log('edit',this.data.skuId)
           let listData = response.data
           const newArray = listData.filter(item => item.skuId !== this.data.skuId);
           console.log(newArray)
           productData = newArray
          }

          console.log(productData)
              let response1 = productData
          let tmp=[];
          if(response1 instanceof Array){

            productData.forEach(element => {
            tmp.push(element.skuId)           
          });
          console.log(tmp,`${control.value}`);
          return !tmp.includes(`${control.value}`) ? null : { usernameTaken: true };
        }else{
          return null
        }
        })
      );
  }

  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);
      tmp.id = this.data.id
    }  
    // 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.CreateProductDetails (tmp).subscribe(res => {
      if (res.status == 200) {
console.log(res)
this.windowRef.close(1);
      }else{
        this.windowRef.close(0);
      }
    })

}
}
