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

import { CasinoMoney } from '../models/casino-money';
import { CasinoMoneyPagination } from '../models/casino-money-pagination';

@Injectable({
  providedIn: 'root',
})
export class CasinoMoneyService {
  // Private
  private __pagination = new BehaviorSubject<CasinoMoneyPagination | undefined>(
    undefined
  );
  private __casinoMoney = new BehaviorSubject<CasinoMoney | undefined>(
    undefined
  );
  private __casinoMoneys = new BehaviorSubject<CasinoMoney[] | undefined>(
    undefined
  );

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

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

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

  /**
   * Getter for casinoMoney
   */
  get casinoMoney$(): Observable<CasinoMoney | undefined> {
    return this.__casinoMoney.asObservable();
  }

  /**
   * Getter for casinoMoneys
   */
  get casinoMoneys$(): Observable<CasinoMoney[] | undefined> {
    return this.__casinoMoneys.asObservable();
  }

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

  /**
   * Get casinoMoneys
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getCasinoMoneys(
    page: number = 0,
    size: number = 10,
    sort: string = 'name',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: CasinoMoneyPagination;
    casinoMoneys: CasinoMoney[];
  }> {
    return this._httpClient
      .get<{ pagination: CasinoMoneyPagination; casinoMoneys: CasinoMoney[] }>(
        'api/apps/member/casino-money/casino-moneys',
        {
          params: {
            page: '' + page,
            size: '' + size,
            sort,
            order,
            search,
          },
        }
      )
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__casinoMoneys.next(response.casinoMoneys);
        })
      );
  }

  /**
   * Get product by id
   */
  getCasinoMoneyById(id: string | null): Observable<CasinoMoney> {
    return this.__casinoMoneys.pipe(
      take(1),
      map((casinoMoneys) => {
        // Find the product
        const casinoMoney =
          casinoMoneys?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__casinoMoney.next(casinoMoney);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createCasinoMoney(): Observable<CasinoMoney> {
    return this.casinoMoneys$.pipe(
      take(1),
      switchMap((casinoMoneys) =>
        this._httpClient
          .post<CasinoMoney>('api/apps/member/casino-money/product', {})
          .pipe(
            map((newCasinoMoney) => {
              // Update the casinoMoneys with the new product
              if (!!casinoMoneys) {
                this.__casinoMoneys.next([newCasinoMoney, ...casinoMoneys]);
              }

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