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

import { Evolution } from '../models/evolution';
import { EvolutionPagination } from '../models/evolution-pagination';

@Injectable({
  providedIn: 'root',
})
export class EvolutionService {
  // Private
  private __pagination = new BehaviorSubject<EvolutionPagination | undefined>(
    undefined
  );
  private __evolution = new BehaviorSubject<Evolution | undefined>(undefined);
  private __evolutions = new BehaviorSubject<Evolution[] | undefined>(
    undefined
  );

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

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

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

  /**
   * Getter for evolution
   */
  get evolution$(): Observable<Evolution | undefined> {
    return this.__evolution.asObservable();
  }

  /**
   * Getter for evolutions
   */
  get evolutions$(): Observable<Evolution[] | undefined> {
    return this.__evolutions.asObservable();
  }

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

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

  /**
   * Get product by id
   */
  getEvolutionById(id: string | null): Observable<Evolution> {
    return this.__evolutions.pipe(
      take(1),
      map((evolutions) => {
        // Find the product
        const evolution =
          evolutions?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__evolution.next(evolution);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createEvolution(): Observable<Evolution> {
    return this.evolutions$.pipe(
      take(1),
      switchMap((evolutions) =>
        this._httpClient
          .post<Evolution>('api/apps/game/evolution/product', {})
          .pipe(
            map((newEvolution) => {
              // Update the evolutions with the new product
              if (!!evolutions) {
                this.__evolutions.next([newEvolution, ...evolutions]);
              }

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