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

import { Slot } from '../models/slot';
import { SlotPagination } from '../models/slot-pagination';

@Injectable({
  providedIn: 'root',
})
export class SlotService {
  // Private
  private __pagination = new BehaviorSubject<SlotPagination | undefined>(
    undefined
  );
  private __slot = new BehaviorSubject<Slot | undefined>(undefined);
  private __slots = new BehaviorSubject<Slot[] | undefined>(undefined);

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

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

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

  /**
   * Getter for slot
   */
  get slot$(): Observable<Slot | undefined> {
    return this.__slot.asObservable();
  }

  /**
   * Getter for slots
   */
  get slots$(): Observable<Slot[] | undefined> {
    return this.__slots.asObservable();
  }

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

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

  /**
   * Get product by id
   */
  getSlotById(id: string | null): Observable<Slot> {
    return this.__slots.pipe(
      take(1),
      map((slots) => {
        // Find the product
        const slot = slots?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__slot.next(slot);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createSlot(): Observable<Slot> {
    return this.slots$.pipe(
      take(1),
      switchMap((slots) =>
        this._httpClient.post<Slot>('api/apps/game/slot/product', {}).pipe(
          map((newSlot) => {
            // Update the slots with the new product
            if (!!slots) {
              this.__slots.next([newSlot, ...slots]);
            }

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