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

import { Casino } from '../models/casino';
import { CasinoPagination } from '../models/casino-pagination';

@Injectable({
  providedIn: 'root',
})
export class CasinoService {
  // Private
  private __pagination = new BehaviorSubject<CasinoPagination | undefined>(
    undefined
  );
  private __casino = new BehaviorSubject<Casino | undefined>(undefined);
  private __casinos = new BehaviorSubject<Casino[] | undefined>(undefined);

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

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

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

  /**
   * Getter for casino
   */
  get casino$(): Observable<Casino | undefined> {
    return this.__casino.asObservable();
  }

  /**
   * Getter for casinos
   */
  get casinos$(): Observable<Casino[] | undefined> {
    return this.__casinos.asObservable();
  }

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

  /**
   * Get casinos
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getCasinos(
    page: number = 0,
    size: number = 10,
    sort: string = 'nickname',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: CasinoPagination;
    casinos: Casino[];
  }> {
    return this._httpClient
      .get<{ pagination: CasinoPagination; casinos: Casino[] }>(
        'api/apps/game/casino/casinos',
        {
          params: {
            page: '' + page,
            size: '' + size,
            sort,
            order,
            search,
          },
        }
      )
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__casinos.next(response.casinos);
        })
      );
  }

  /**
   * Get product by id
   */
  getCasinoById(id: string | null): Observable<Casino> {
    return this.__casinos.pipe(
      take(1),
      map((casinos) => {
        // Find the product
        const casino = casinos?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__casino.next(casino);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createCasino(): Observable<Casino> {
    return this.casinos$.pipe(
      take(1),
      switchMap((casinos) =>
        this._httpClient.post<Casino>('api/apps/game/casino/product', {}).pipe(
          map((newCasino) => {
            // Update the casinos with the new product
            if (!!casinos) {
              this.__casinos.next([newCasino, ...casinos]);
            }

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