import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { Observable, throwError } from 'rxjs';
import { catchError, debounceTime, distinctUntilChanged, filter, map, switchMap, tap } from 'rxjs/operators';
import { Customer } from 'src/app/models/customer.model';
import { ResultApi } from 'src/app/models/result-api.model';
import { CustomerService } from 'src/app/services/customer.service';

@Component({
  selector: 'app-list-customer',
  templateUrl: './list-customer.component.html',
  styleUrls: ['./list-customer.component.scss']
})
export class ListCustomerComponent implements OnInit {
  customer$: Observable<Customer[]>;
  result$: Observable<any>;
  public errorObject = null;
  public isloading = false;
  duration = 300;
  public form: FormGroup;

  constructor(private readonly customerService: CustomerService) {
    this.form = new FormGroup({
      document: new FormControl('', []),
      name: new FormControl('', []),
    });
  }

  ngOnInit(): void {

  }

  async searchCustomer(name: string) {
    console.log('Pesquisando...');
    this.isloading = true;
    this.errorObject = null;
    this.customer$ = this.customerService.getCustomer(name.toUpperCase()).pipe(
      tap(() => this.isloading = false),
      catchError(err => {
        this.isloading = false;
        this.errorObject = err;
        return throwError(err);
      }));
  }

  async searchCustomerByQuery() {
    const document = this.form.get('document').value;
    const name = this.form.get('name').value;
    console.log('Pesquisando...' + document + ' ' + name);
    this.isloading = true;
    this.errorObject = null;
    if ( document ) {
      this.customer$ = this.customerService
      .getCustomerByQuery('document', document)
      .pipe(
        tap(() => this.isloading = false),
        catchError(err => {
          this.isloading = false;
          this.errorObject = err;
          return throwError(err);
        }));
    } else {
      this.customer$ = this.customerService
      .getCustomerByQuery('name', name.toUpperCase())
      .pipe(
        tap(() => this.isloading = false),
        catchError(err => {
          this.isloading = false;
          this.errorObject = err;
          return throwError(err);
        }));
    }
  }

}
