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

import { PartnerRecommendation } from '../models/partner-recommendation';
import { PartnerRecommendationPagination } from '../models/partner-recommendation-pagination';

@Injectable({
  providedIn: 'root',
})
export class PartnerRecommendationService {
  // Private
  private __pagination = new BehaviorSubject<
    PartnerRecommendationPagination | undefined
  >(undefined);
  private __partnerRecommendation = new BehaviorSubject<
    PartnerRecommendation | undefined
  >(undefined);
  private __partnerRecommendations = new BehaviorSubject<
    PartnerRecommendation[] | undefined
  >(undefined);

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

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

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

  /**
   * Getter for partnerRecommendation
   */
  get partnerRecommendation$(): Observable<PartnerRecommendation | undefined> {
    return this.__partnerRecommendation.asObservable();
  }

  /**
   * Getter for partnerRecommendations
   */
  get partnerRecommendations$(): Observable<
    PartnerRecommendation[] | undefined
  > {
    return this.__partnerRecommendations.asObservable();
  }

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

  /**
   * Get partnerRecommendations
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getPartnerRecommendations(
    page: number = 0,
    size: number = 10,
    sort: string = 'name',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: PartnerRecommendationPagination;
    partnerRecommendations: PartnerRecommendation[];
  }> {
    return this._httpClient
      .get<{
        pagination: PartnerRecommendationPagination;
        partnerRecommendations: PartnerRecommendation[];
      }>('api/apps/member/partner-recommendation/partner-recommendations', {
        params: {
          page: '' + page,
          size: '' + size,
          sort,
          order,
          search,
        },
      })
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__partnerRecommendations.next(response.partnerRecommendations);
        })
      );
  }

  /**
   * Get product by id
   */
  getPartnerRecommendationById(
    id: string | null
  ): Observable<PartnerRecommendation> {
    return this.__partnerRecommendations.pipe(
      take(1),
      map((partnerRecommendations) => {
        // Find the product
        const partnerRecommendation =
          partnerRecommendations?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__partnerRecommendation.next(partnerRecommendation);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createPartnerRecommendation(): Observable<PartnerRecommendation> {
    return this.partnerRecommendations$.pipe(
      take(1),
      switchMap((partnerRecommendations) =>
        this._httpClient
          .post<PartnerRecommendation>(
            'api/apps/member/partner-recommendation/product',
            {}
          )
          .pipe(
            map((newPartnerRecommendation) => {
              // Update the partnerRecommendations with the new product
              if (!!partnerRecommendations) {
                this.__partnerRecommendations.next([
                  newPartnerRecommendation,
                  ...partnerRecommendations,
                ]);
              }

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