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

import { TodayBet } from '../models/today-bet';
import { TodayBetPagination } from '../models/today-bet-pagination';

@Injectable({
  providedIn: 'root',
})
export class TodayBetService {
  // Private
  private __pagination = new BehaviorSubject<TodayBetPagination | undefined>(
    undefined
  );
  private __todayBet = new BehaviorSubject<TodayBet | undefined>(undefined);
  private __todayBets = new BehaviorSubject<TodayBet[] | undefined>(undefined);

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

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

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

  /**
   * Getter for todayBet
   */
  get todayBet$(): Observable<TodayBet | undefined> {
    return this.__todayBet.asObservable();
  }

  /**
   * Getter for todayBets
   */
  get todayBets$(): Observable<TodayBet[] | undefined> {
    return this.__todayBets.asObservable();
  }

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

  /**
   * Get TodayBets
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getTodayBets(
    page: number = 0,
    size: number = 10,
    sort: string = 'name',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: TodayBetPagination;
    todayBets: TodayBet[];
  }> {
    return this._httpClient
      .get<{
        pagination: TodayBetPagination;
        todayBets: TodayBet[];
      }>('api/apps/report/today-bet/today-bets', {
        params: {
          page: '' + page,
          size: '' + size,
          sort,
          order,
          search,
        },
      })
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__todayBets.next(response.todayBets);
        })
      );
  }

  /**
   * Get product by id
   */
  getTodayBetById(id: string | null): Observable<TodayBet> {
    return this.__todayBets.pipe(
      take(1),
      map((todayBets) => {
        // Find the product
        const todayBet = todayBets?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__todayBet.next(todayBet);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createTodayBet(): Observable<TodayBet> {
    return this.todayBets$.pipe(
      take(1),
      switchMap((todayBets) =>
        this._httpClient
          .post<TodayBet>('api/apps/report/today-bet/product', {})
          .pipe(
            map((newTodayBet) => {
              // Update the todayBets with the new product
              if (!!todayBets) {
                this.__todayBets.next([newTodayBet, ...todayBets]);
              }

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