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

import { Powerball } from '../models/powerball';
import { PowerballPagination } from '../models/powerball-pagination';

@Injectable({
  providedIn: 'root',
})
export class PowerballService {
  // Private
  private __pagination = new BehaviorSubject<PowerballPagination | undefined>(
    undefined
  );
  private __powerball = new BehaviorSubject<Powerball | undefined>(undefined);
  private __powerballs = new BehaviorSubject<Powerball[] | undefined>(
    undefined
  );

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

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

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

  /**
   * Getter for powerball
   */
  get powerball$(): Observable<Powerball | undefined> {
    return this.__powerball.asObservable();
  }

  /**
   * Getter for powerballs
   */
  get powerballs$(): Observable<Powerball[] | undefined> {
    return this.__powerballs.asObservable();
  }

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

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

  /**
   * Get product by id
   */
  getPowerballById(id: string | null): Observable<Powerball> {
    return this.__powerballs.pipe(
      take(1),
      map((powerballs) => {
        // Find the product
        const powerball =
          powerballs?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__powerball.next(powerball);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createPowerball(): Observable<Powerball> {
    return this.powerballs$.pipe(
      take(1),
      switchMap((powerballs) =>
        this._httpClient
          .post<Powerball>('api/apps/game/powerball/product', {})
          .pipe(
            map((newPowerball) => {
              // Update the powerballs with the new product
              if (!!powerballs) {
                this.__powerballs.next([newPowerball, ...powerballs]);
              }

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