import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {
  BehaviorSubject,
  filter,
  map,
  Observable,
  of,
  switchMap,
  take,
  tap,
  throwError,
} from 'rxjs';

import { PaymentLog } from '../models/payment-log';
import { PaymentLogPagination } from '../models/payment-log-pagination';

@Injectable({
  providedIn: 'root',
})
export class PaymentLogService {
  // Private
  private __pagination = new BehaviorSubject<PaymentLogPagination | undefined>(
    undefined
  );
  private __paymentLog = new BehaviorSubject<PaymentLog | undefined>(undefined);
  private __paymentLogs = new BehaviorSubject<PaymentLog[] | undefined>(
    undefined
  );

  /**
   * Constructor
   */
  constructor(private _httpClient: HttpClient) {}

  // -----------------------------------------------------------------------------------------------------
  // @ Accessors
  // -----------------------------------------------------------------------------------------------------

  /**
   * Getter for pagination
   */
  get pagination$(): Observable<PaymentLogPagination | undefined> {
    return this.__pagination.asObservable();
  }

  /**
   * Getter for paymentLog
   */
  get paymentLog$(): Observable<PaymentLog | undefined> {
    return this.__paymentLog.asObservable();
  }

  /**
   * Getter for paymentLogs
   */
  get paymentLogs$(): Observable<PaymentLog[] | undefined> {
    return this.__paymentLogs.asObservable();
  }

  // -----------------------------------------------------------------------------------------------------
  // @ Public methods
  // -----------------------------------------------------------------------------------------------------

  /**
   * Get paymentLogs
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getPaymentLogs(
    page: number = 0,
    size: number = 10,
    sort: string = 'name',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: PaymentLogPagination;
    paymentLogs: PaymentLog[];
  }> {
    return this._httpClient
      .get<{
        pagination: PaymentLogPagination;
        paymentLogs: PaymentLog[];
      }>('api/apps/report/payment-log/payment-logs', {
        params: {
          page: '' + page,
          size: '' + size,
          sort,
          order,
          search,
        },
      })
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__paymentLogs.next(response.paymentLogs);
        })
      );
  }

  /**
   * Get product by id
   */
  getPaymentLogById(id: string | null): Observable<PaymentLog> {
    return this.__paymentLogs.pipe(
      take(1),
      map((paymentLogs) => {
        // Find the product
        const paymentLog =
          paymentLogs?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__paymentLog.next(paymentLog);

        // Return the product
        return paymentLog;
      }),
      switchMap((product) => {
        if (!product) {
          return throwError('Could not found product with id of ' + id + '!');
        }

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createPaymentLog(): Observable<PaymentLog> {
    return this.paymentLogs$.pipe(
      take(1),
      switchMap((paymentLogs) =>
        this._httpClient
          .post<PaymentLog>('api/apps/report/payment-log/product', {})
          .pipe(
            map((newPaymentLog) => {
              // Update the paymentLogs with the new product
              if (!!paymentLogs) {
                this.__paymentLogs.next([newPaymentLog, ...paymentLogs]);
              }

              // Return the new product
              return newPaymentLog;
            })
          )
      )
    );
  }
}
