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

import { PartnerCalculate } from '../models/partner-calculate';
import { PartnerCalculatePagination } from '../models/partner-calculate-pagination';

@Injectable({
  providedIn: 'root',
})
export class PartnerCalculateService {
  // Private
  private __pagination = new BehaviorSubject<
    PartnerCalculatePagination | undefined
  >(undefined);
  private __partnerCalculate = new BehaviorSubject<
    PartnerCalculate | undefined
  >(undefined);
  private __partnerCalculates = new BehaviorSubject<
    PartnerCalculate[] | undefined
  >(undefined);

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

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

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

  /**
   * Getter for partnerCalculate
   */
  get partnerCalculate$(): Observable<PartnerCalculate | undefined> {
    return this.__partnerCalculate.asObservable();
  }

  /**
   * Getter for partnerCalculates
   */
  get partnerCalculates$(): Observable<PartnerCalculate[] | undefined> {
    return this.__partnerCalculates.asObservable();
  }

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

  /**
   * Get partnerCalculates
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getPartnerCalculates(
    page: number = 0,
    size: number = 10,
    sort: string = 'nickname',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: PartnerCalculatePagination;
    partnerCalculates: PartnerCalculate[];
  }> {
    return this._httpClient
      .get<{
        pagination: PartnerCalculatePagination;
        partnerCalculates: PartnerCalculate[];
      }>('api/apps/bank/partner-calculate/partner-calculates', {
        params: {
          page: '' + page,
          size: '' + size,
          sort,
          order,
          search,
        },
      })
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__partnerCalculates.next(response.partnerCalculates);
        })
      );
  }

  /**
   * Get product by id
   */
  getPartnerCalculateById(id: string | null): Observable<PartnerCalculate> {
    return this.__partnerCalculates.pipe(
      take(1),
      map((partnerCalculates) => {
        // Find the product
        const partnerCalculate =
          partnerCalculates?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__partnerCalculate.next(partnerCalculate);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createPartnerCalculate(): Observable<PartnerCalculate> {
    return this.partnerCalculates$.pipe(
      take(1),
      switchMap((partnerCalculates) =>
        this._httpClient
          .post<PartnerCalculate>('api/apps/bank/partner-calculate/product', {})
          .pipe(
            map((newPartnerCalculate) => {
              // Update the partnerCalculates with the new product
              if (!!partnerCalculates) {
                this.__partnerCalculates.next([
                  newPartnerCalculate,
                  ...partnerCalculates,
                ]);
              }

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