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

import { Partner } from '../models/partner';
import { PartnerPagination } from '../models/partner-pagination';

@Injectable({
  providedIn: 'root',
})
export class PartnerService {
  // Private
  private __pagination = new BehaviorSubject<PartnerPagination | undefined>(
    undefined
  );
  private __partner = new BehaviorSubject<Partner | undefined>(undefined);
  private __partners = new BehaviorSubject<Partner[] | undefined>(undefined);

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

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

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

  /**
   * Getter for partner
   */
  get partner$(): Observable<Partner | undefined> {
    return this.__partner.asObservable();
  }

  /**
   * Getter for partners
   */
  get partners$(): Observable<Partner[] | undefined> {
    return this.__partners.asObservable();
  }

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

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

  /**
   * Get product by id
   */
  getPartnerById(id: string | null): Observable<Partner> {
    return this.__partners.pipe(
      take(1),
      map((partners) => {
        // Find the product
        const partner = partners?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__partner.next(partner);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createPartner(): Observable<Partner> {
    return this.partners$.pipe(
      take(1),
      switchMap((partners) =>
        this._httpClient
          .post<Partner>('api/apps/member/partner/product', {})
          .pipe(
            map((newPartner) => {
              // Update the partners with the new product
              if (!!partners) {
                this.__partners.next([newPartner, ...partners]);
              }

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