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

import { CouponLog } from '../models/coupon-log';
import { CouponLogPagination } from '../models/coupon-log-pagination';

@Injectable({
  providedIn: 'root',
})
export class CouponLogService {
  // Private
  private __pagination = new BehaviorSubject<CouponLogPagination | undefined>(
    undefined
  );
  private __couponLog = new BehaviorSubject<CouponLog | undefined>(undefined);
  private __couponLogs = new BehaviorSubject<CouponLog[] | undefined>(
    undefined
  );

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

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

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

  /**
   * Getter for couponLog
   */
  get couponLog$(): Observable<CouponLog | undefined> {
    return this.__couponLog.asObservable();
  }

  /**
   * Getter for couponLogs
   */
  get couponLogs$(): Observable<CouponLog[] | undefined> {
    return this.__couponLogs.asObservable();
  }

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

  /**
   * Get couponLogs
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getCouponLogs(
    page: number = 0,
    size: number = 10,
    sort: string = 'name',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: CouponLogPagination;
    couponLogs: CouponLog[];
  }> {
    return this._httpClient
      .get<{
        pagination: CouponLogPagination;
        couponLogs: CouponLog[];
      }>('api/apps/member/coupon-log/coupon-logs', {
        params: {
          page: '' + page,
          size: '' + size,
          sort,
          order,
          search,
        },
      })
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__couponLogs.next(response.couponLogs);
        })
      );
  }

  /**
   * Get product by id
   */
  getCouponLogById(id: string | null): Observable<CouponLog> {
    return this.__couponLogs.pipe(
      take(1),
      map((couponLogs) => {
        // Find the product
        const couponLog =
          couponLogs?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__couponLog.next(couponLog);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createCouponLog(): Observable<CouponLog> {
    return this.couponLogs$.pipe(
      take(1),
      switchMap((couponLogs) =>
        this._httpClient
          .post<CouponLog>('api/apps/member/coupon-log/product', {})
          .pipe(
            map((newCouponLog) => {
              // Update the couponLogs with the new product
              if (!!couponLogs) {
                this.__couponLogs.next([newCouponLog, ...couponLogs]);
              }

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