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-money-log';
import { CouponMoneyLogPagination } from '../models/coupon-money-log-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-money-log/coupon-money-logs', {
        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-money-log/product', {})
          .pipe(
            map((newCouponMoneyLog) => {
              // Update the couponMoneyLogs with the new product
              if (!!couponMoneyLogs) {
                this.__couponMoneyLogs.next([
                  newCouponMoneyLog,
                  ...couponMoneyLogs,
                ]);
              }

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