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

import { Statistics } from '../models/statistics';
import { CasinoStatistics } from '../models/casino-statistics';
import { SlotStatistics } from '../models/slot-statistics';
import { PowerballStatistics } from '../models/powerball-statistics';
import { StatisticsPagination } from '../models/statistics-pagination';

@Injectable({
  providedIn: 'root',
})
export class StatisticsService {
  // Private
  private __pagination = new BehaviorSubject<StatisticsPagination | undefined>(
    undefined
  );
  private __statistics = new BehaviorSubject<Statistics[] | undefined>(
    undefined
  );
  private __casinoStatistics = new BehaviorSubject<
    CasinoStatistics | undefined
  >(undefined);
  private __slotStatistics = new BehaviorSubject<SlotStatistics | undefined>(
    undefined
  );
  private __powerballStatistics = new BehaviorSubject<
    PowerballStatistics | undefined
  >(undefined);

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

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

  /**
   * Getter for pagination
   */
  get pagination$(): Observable<StatisticsPagination | undefined> {
    return this.__pagination.asObservable();
  }
  /**
   * Getter for statistics
   */
  get statistics$(): Observable<Statistics[] | undefined> {
    return this.__statistics.asObservable();
  }

  /**
   * Getter for casino-statistics
   */
  get casinoStatistics$(): Observable<CasinoStatistics | undefined> {
    return this.__casinoStatistics.asObservable();
  }
  // -----------------------------------------------------------------------------------------------------
  // @ Public methods
  // -----------------------------------------------------------------------------------------------------

  /**
   * Getter for casino-statistics
   */
  get slotStatistics$(): Observable<SlotStatistics | undefined> {
    return this.__slotStatistics.asObservable();
  }
  // -----------------------------------------------------------------------------------------------------
  // @ Public methods
  // -----------------------------------------------------------------------------------------------------

  /**
   * Getter for casino-statistics
   */
  get powerballStatistics$(): Observable<PowerballStatistics | undefined> {
    return this.__powerballStatistics.asObservable();
  }
  // -----------------------------------------------------------------------------------------------------
  // @ Public methods
  // -----------------------------------------------------------------------------------------------------

  /**
   * Get statistics
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getStatistics(
    page: number = 0,
    size: number = 10,
    sort: string = 'casinoUse',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: StatisticsPagination;
    statistics: Statistics[];
  }> {
    return this._httpClient
      .get<{
        pagination: StatisticsPagination;
        statistics: Statistics[];
      }>('api/apps/report/statistics', {
        params: {
          page: '' + page,
          size: '' + size,
          sort,
          order,
          search,
        },
      })
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__statistics.next(response.statistics);
        })
      );
  }

  /**
   * Get product by id
   */
  getStatisticsById(id: string | null): Observable<Statistics[]> {
    return this.__statistics.pipe(
      take(1),
      map((statistics) => {
        // Find the product
        statistics?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__statistics.next(statistics);

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

        return of(product);
      })
    );
  }

  /**
   * Get product by type
   */
  getCasinoStatisticsByType(type: string | null): Observable<CasinoStatistics> {
    return this.__statistics.pipe(
      take(1),
      map((statistics) => {
        // Find the product
        const casinoStatistics =
          statistics?.find((item) => item.id === type) || undefined;

        // Update the product
        this.__casinoStatistics.next(casinoStatistics);

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

        return of(product);
      })
    );
  }
  getSlotStatisticsByType(type: string | null): Observable<SlotStatistics> {
    return this.__statistics.pipe(
      take(1),
      map((statistics) => {
        // Find the product
        const slotStatistics =
          statistics?.find((item) => item.id === type) || undefined;

        // Update the product
        this.__slotStatistics.next(slotStatistics);

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

        return of(product);
      })
    );
  }
  getPowerballStatisticsByType(
    type: string | null
  ): Observable<PowerballStatistics> {
    return this.__statistics.pipe(
      take(1),
      map((statistics) => {
        // Find the product
        const powerballStatistics =
          statistics?.find((item) => item.id === type) || undefined;

        // Update the product
        this.__powerballStatistics.next(powerballStatistics);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createStatistics(): Observable<Statistics> {
    return this.statistics$.pipe(
      take(1),
      switchMap((statistics) =>
        this._httpClient
          .post<Statistics>('api/apps/report/statistics/product', {})
          .pipe(
            map((newStatistics) => {
              // Update the statistics with the new product
              if (!!statistics) {
                this.__statistics.next([newStatistics, ...statistics]);
              }

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