import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
import { environment } from 'src/environments/environment';
import { CreatePaymentPartner } from '../models/create-payment-partner.model';
import { Partner } from '../models/partner.model';
import { Partners } from '../models/partners.model';
import { PaymentPartner } from '../models/payment-partner.model';
import { ExtractPartner } from '../models/extract-partner.model';

@Injectable({
  providedIn: 'root'
})
export class PartnerService {

  constructor(
    private readonly http: HttpClient
  ) { }


  getPartner(cpf: string) {
    const url = environment.url + `partners/${cpf}`;
    return this.http.get<any>(url);
  }

  getPartnerByQuery(type: string, cpf: string, name: string) {
    try {
      let url = environment.url + `partners?`;
      url += `type=${type}`;
      if (cpf != null) {
        url += `&cpf=${cpf}`;
      }
      if (name != null) {
        url += `&name=${name}`;
      }
      return this.http.get<Partners[]>(url).pipe(
        map((response) => {
          console.log(response);
          return response;
        }),
        tap(() => {})
      );
    } catch (error) {
      console.log(error);
    }

  }

  createOrReplace(partner: Partner) {
    const url = environment.url + `partners/create`;
    return this.http.post<Partner>(url, partner);
  }

  getPayment(partnerId: number, type: number, month: string, year: string){
    const url = environment.url + `partners/payment?partnerId=${partnerId}&type=${type}&month=${month}&year=${year}`;
    console.log(url);
    return this.http.get<PaymentPartner[]>(url);
  }

  createPayment(data: CreatePaymentPartner[]) {
      const url = environment.url + `partners/paymentcreate`;
      console.log(url);
      return this.http.post(url, data);
  }

  getExtractPartner(partnerId: number, start: Date, end: Date) {
    const url = environment.url + `partners/extract/${partnerId}`;
    const params = new HttpParams()
          .set('start', start.toISOString())
          .set('end', end.toISOString());
    return this.http.get<ExtractPartner[]>(url, {params});
  }

}
