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

import { Coupon } from '../models/coupon';
import { CouponPagination } from '../models/coupon-pagination';

@Injectable({
  providedIn: 'root',
})
export class CouponService {
  // Private
  private __pagination = new BehaviorSubject<CouponPagination | undefined>(
    undefined
  );
  private __coupon = new BehaviorSubject<Coupon | undefined>(undefined);
  private __coupons = new BehaviorSubject<Coupon[] | undefined>(undefined);

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

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

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

  /**
   * Getter for coupon
   */
  get coupon$(): Observable<Coupon | undefined> {
    return this.__coupon.asObservable();
  }

  /**
   * Getter for coupons
   */
  get coupons$(): Observable<Coupon[] | undefined> {
    return this.__coupons.asObservable();
  }

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

  /**
   * Get coupons
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getCoupons(
    page: number = 0,
    size: number = 10,
    sort: string = 'name',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: CouponPagination;
    coupons: Coupon[];
  }> {
    return this._httpClient
      .get<{
        pagination: CouponPagination;
        coupons: Coupon[];
      }>('api/apps/member/coupon/coupons', {
        params: {
          page: '' + page,
          size: '' + size,
          sort,
          order,
          search,
        },
      })
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__coupons.next(response.coupons);
        })
      );
  }

  /**
   * Get product by id
   */
  getCouponById(id: string | null): Observable<Coupon> {
    return this.__coupons.pipe(
      take(1),
      map((coupons) => {
        // Find the product
        const coupon = coupons?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__coupon.next(coupon);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createCoupon(): Observable<Coupon> {
    return this.coupons$.pipe(
      take(1),
      switchMap((coupons) =>
        this._httpClient
          .post<Coupon>('api/apps/member/coupon/product', {})
          .pipe(
            map((newCoupon) => {
              // Update the coupons with the new product
              if (!!coupons) {
                this.__coupons.next([newCoupon, ...coupons]);
              }

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