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

import { WebCalculate } from '../models/web-calculate';
import { WebCalculatePagination } from '../models/web-calculate-pagination';

@Injectable({
  providedIn: 'root',
})
export class WebCalculateService {
  // Private
  private __pagination = new BehaviorSubject<
    WebCalculatePagination | undefined
  >(undefined);
  private __webCalculate = new BehaviorSubject<WebCalculate | undefined>(
    undefined
  );
  private __webCalculates = new BehaviorSubject<WebCalculate[] | undefined>(
    undefined
  );

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

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

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

  /**
   * Getter for webCalculate
   */
  get webCalculate$(): Observable<WebCalculate | undefined> {
    return this.__webCalculate.asObservable();
  }

  /**
   * Getter for webCalculates
   */
  get webCalculates$(): Observable<WebCalculate[] | undefined> {
    return this.__webCalculates.asObservable();
  }

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

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

  /**
   * Get product by id
   */
  getWebCalculateById(id: string | null): Observable<WebCalculate> {
    return this.__webCalculates.pipe(
      take(1),
      map((webCalculates) => {
        // Find the product
        const webCalculate =
          webCalculates?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__webCalculate.next(webCalculate);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createWebCalculate(): Observable<WebCalculate> {
    return this.webCalculates$.pipe(
      take(1),
      switchMap((webCalculates) =>
        this._httpClient
          .post<WebCalculate>('api/apps/bank/web-calculate/product', {})
          .pipe(
            map((newWebCalculate) => {
              // Update the webCalculates with the new product
              if (!!webCalculates) {
                this.__webCalculates.next([newWebCalculate, ...webCalculates]);
              }

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