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

import { Deposit } from '../models/deposit';
import { DepositPagination } from '../models/deposit-pagination';

@Injectable({
  providedIn: 'root',
})
export class DepositService {
  // Private
  private __pagination = new BehaviorSubject<DepositPagination | undefined>(
    undefined
  );
  private __deposit = new BehaviorSubject<Deposit | undefined>(undefined);
  private __deposits = new BehaviorSubject<Deposit[] | undefined>(undefined);

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

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

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

  /**
   * Getter for deposit
   */
  get deposit$(): Observable<Deposit | undefined> {
    return this.__deposit.asObservable();
  }

  /**
   * Getter for deposits
   */
  get deposits$(): Observable<Deposit[] | undefined> {
    return this.__deposits.asObservable();
  }

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

  /**
   * Get deposits
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getDeposits(
    page: number = 0,
    size: number = 10,
    sort: string = 'nickname',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: DepositPagination;
    deposits: Deposit[];
  }> {
    return this._httpClient
      .get<{ pagination: DepositPagination; deposits: Deposit[] }>(
        'api/apps/bank/deposit/deposits',
        {
          params: {
            page: '' + page,
            size: '' + size,
            sort,
            order,
            search,
          },
        }
      )
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__deposits.next(response.deposits);
        })
      );
  }

  /**
   * Get product by id
   */
  getDepositById(id: string | null): Observable<Deposit> {
    return this.__deposits.pipe(
      take(1),
      map((deposits) => {
        // Find the product
        const deposit = deposits?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__deposit.next(deposit);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createDeposit(): Observable<Deposit> {
    return this.deposits$.pipe(
      take(1),
      switchMap((deposits) =>
        this._httpClient
          .post<Deposit>('api/apps/bank/deposit/product', {})
          .pipe(
            map((newDeposit) => {
              // Update the deposits with the new product
              if (!!deposits) {
                this.__deposits.next([newDeposit, ...deposits]);
              }

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