import { Component, EventEmitter, Input, OnDestroy, OnInit, Output } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Subscription } from 'rxjs';
import { ResultApi } from 'src/app/models/result-api.model';
import { CustomerService } from 'src/app/services/customer.service';

@Component({
  selector: 'app-pre-customer',
  templateUrl: './pre-customer.component.html',
  styleUrls: ['./pre-customer.component.scss']
})
export class PreCustomerComponent implements OnInit, OnDestroy {


  @Output() public submitForm: EventEmitter<any> = new EventEmitter();
  searchSubscription: Subscription;

  public myForm: FormGroup = this.fb.group({
    document: ['', Validators.required],
    name: ['', Validators.required],
    cellPhone: ['', Validators.required],
  });

  constructor(
    private fb: FormBuilder,
    private customerService: CustomerService) { }

  public onConfirmAction(): void {
    localStorage.setItem('preCustomer', JSON.stringify(this.myForm.value));
    this.submitForm.emit(this.myForm.value);
  }

  ngOnInit(): void {
  }

  ngOnDestroy(): void {
    if (this.searchSubscription){
      this.searchSubscription.unsubscribe();
    }
  }

  async searchCustomer(){
    const document = this.myForm.get('document').value;
    this.searchSubscription = this.customerService.getCustomerbyCpf(document)
      .subscribe(result => {
        if (result.data != null){
          this.myForm.patchValue({name: result.data.name, cellPhone: result.data.cellPhone});
        }
      });

  }

}
