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

import { DailyPartner } from '../models/daily-partner';
import { DailyPartnerPagination } from '../models/daily-partner-pagination';

@Injectable({
  providedIn: 'root',
})
export class DailyPartnerService {
  // Private
  private __pagination = new BehaviorSubject<
    DailyPartnerPagination | undefined
  >(undefined);
  private __dailyPartner = new BehaviorSubject<DailyPartner | undefined>(
    undefined
  );
  private __dailyPartners = new BehaviorSubject<DailyPartner[] | undefined>(
    undefined
  );

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

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

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

  /**
   * Getter for dailyPartner
   */
  get dailyPartner$(): Observable<DailyPartner | undefined> {
    return this.__dailyPartner.asObservable();
  }

  /**
   * Getter for dailyPartners
   */
  get dailyPartners$(): Observable<DailyPartner[] | undefined> {
    return this.__dailyPartners.asObservable();
  }

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

  /**
   * Get DailyPartners
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getDailyPartners(
    page: number = 0,
    size: number = 10,
    sort: string = 'name',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: DailyPartnerPagination;
    dailyPartners: DailyPartner[];
  }> {
    return this._httpClient
      .get<{
        pagination: DailyPartnerPagination;
        dailyPartners: DailyPartner[];
      }>('api/apps/report/daily-partners', {
        params: {
          page: '' + page,
          size: '' + size,
          sort,
          order,
          search,
        },
      })
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__dailyPartners.next(response.dailyPartners);
        })
      );
  }

  /**
   * Get product by id
   */
  getDailyPartnerById(id: string | null): Observable<DailyPartner> {
    return this.__dailyPartners.pipe(
      take(1),
      map((dailyPartners) => {
        // Find the product
        const dailyPartner =
          dailyPartners?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__dailyPartner.next(dailyPartner);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createDailyPartner(): Observable<DailyPartner> {
    return this.dailyPartners$.pipe(
      take(1),
      switchMap((dailyPartners) =>
        this._httpClient
          .post<DailyPartner>('api/apps/report/daily-partner/product', {})
          .pipe(
            map((newDailyPartner) => {
              // Update the dailyPartners with the new product
              if (!!dailyPartners) {
                this.__dailyPartners.next([newDailyPartner, ...dailyPartners]);
              }

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