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

import { Withdraw } from '../models/withdraw';
import { WithdrawPagination } from '../models/withdraw-pagination';

@Injectable({
  providedIn: 'root',
})
export class WithdrawService {
  // Private
  private __pagination = new BehaviorSubject<WithdrawPagination | undefined>(
    undefined
  );
  private __withdraw = new BehaviorSubject<Withdraw | undefined>(undefined);
  private __withdraws = new BehaviorSubject<Withdraw[] | undefined>(undefined);

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

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

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

  /**
   * Getter for withdraw
   */
  get withdraw$(): Observable<Withdraw | undefined> {
    return this.__withdraw.asObservable();
  }

  /**
   * Getter for withdraws
   */
  get withdraws$(): Observable<Withdraw[] | undefined> {
    return this.__withdraws.asObservable();
  }

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

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

  /**
   * Get product by id
   */
  getWithdrawById(id: string | null): Observable<Withdraw> {
    return this.__withdraws.pipe(
      take(1),
      map((withdraws) => {
        // Find the product
        const withdraw = withdraws?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__withdraw.next(withdraw);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createWithdraw(): Observable<Withdraw> {
    return this.withdraws$.pipe(
      take(1),
      switchMap((withdraws) =>
        this._httpClient
          .post<Withdraw>('api/apps/bank/withdraw/product', {})
          .pipe(
            map((newWithdraw) => {
              // Update the withdraws with the new product
              if (!!withdraws) {
                this.__withdraws.next([newWithdraw, ...withdraws]);
              }

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