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

import { CouponMoneylog } from '../models/coupon-moneylog';
import { CouponMoneylogPagination } from '../models/coupon-moneylog-pagination';

@Injectable({
  providedIn: 'root',
})
export class CouponMoneylogService {
  // Private
  private __pagination = new BehaviorSubject<
    CouponMoneylogPagination | undefined
  >(undefined);
  private __couponMoneylog = new BehaviorSubject<CouponMoneylog | undefined>(
    undefined
  );
  private __couponMoneylogs = new BehaviorSubject<CouponMoneylog[] | undefined>(
    undefined
  );

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

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

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

  /**
   * Getter for couponMoneylog
   */
  get couponMoneylog$(): Observable<CouponMoneylog | undefined> {
    return this.__couponMoneylog.asObservable();
  }

  /**
   * Getter for couponMoneylogs
   */
  get couponMoneylogs$(): Observable<CouponMoneylog[] | undefined> {
    return this.__couponMoneylogs.asObservable();
  }

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

  /**
   * Get couponMoneylogs
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getCouponMoneylogs(
    page: number = 0,
    size: number = 10,
    sort: string = 'name',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: CouponMoneylogPagination;
    couponMoneylogs: CouponMoneylog[];
  }> {
    return this._httpClient
      .get<{
        pagination: CouponMoneylogPagination;
        couponMoneylogs: CouponMoneylog[];
      }>('api/apps/member/coupon-moneylog/coupon-moneylogs', {
        params: {
          page: '' + page,
          size: '' + size,
          sort,
          order,
          search,
        },
      })
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__couponMoneylogs.next(response.couponMoneylogs);
        })
      );
  }

  /**
   * Get product by id
   */
  getCouponMoneylogById(id: string | null): Observable<CouponMoneylog> {
    return this.__couponMoneylogs.pipe(
      take(1),
      map((couponMoneylogs) => {
        // Find the product
        const couponMoneylog =
          couponMoneylogs?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__couponMoneylog.next(couponMoneylog);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createCouponMoneylog(): Observable<CouponMoneylog> {
    return this.couponMoneylogs$.pipe(
      take(1),
      switchMap((couponMoneylogs) =>
        this._httpClient
          .post<CouponMoneylog>('api/apps/member/coupon-moneylog/product', {})
          .pipe(
            map((newCouponMoneylog) => {
              // Update the couponMoneylogs with the new product
              if (!!couponMoneylogs) {
                this.__couponMoneylogs.next([
                  newCouponMoneylog,
                  ...couponMoneylogs,
                ]);
              }

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