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

import { PartnerStore } from '../models/partner-store';
import { PartnerStorePagination } from '../models/partner-store-pagination';

@Injectable({
  providedIn: 'root',
})
export class PartnerStoreService {
  // Private
  private __pagination = new BehaviorSubject<
    PartnerStorePagination | undefined
  >(undefined);
  private __partnerStore = new BehaviorSubject<PartnerStore | undefined>(
    undefined
  );
  private __partnerStores = new BehaviorSubject<PartnerStore[] | undefined>(
    undefined
  );

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

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

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

  /**
   * Getter for partnerStore
   */
  get partnerStore$(): Observable<PartnerStore | undefined> {
    return this.__partnerStore.asObservable();
  }

  /**
   * Getter for partnerStores
   */
  get partnerStores$(): Observable<PartnerStore[] | undefined> {
    return this.__partnerStores.asObservable();
  }

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

  /**
   * Get partnerStores
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getPartnerStores(
    page: number = 0,
    size: number = 10,
    sort: string = 'name',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: PartnerStorePagination;
    partnerStores: PartnerStore[];
  }> {
    return this._httpClient
      .get<{
        pagination: PartnerStorePagination;
        partnerStores: PartnerStore[];
      }>('api/apps/member/partner-store/partner-stores', {
        params: {
          page: '' + page,
          size: '' + size,
          sort,
          order,
          search,
        },
      })
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__partnerStores.next(response.partnerStores);
        })
      );
  }

  /**
   * Get product by id
   */
  getPartnerStoreById(id: string | null): Observable<PartnerStore> {
    return this.__partnerStores.pipe(
      take(1),
      map((partnerStores) => {
        // Find the product
        const partnerStore =
          partnerStores?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__partnerStore.next(partnerStore);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createPartnerStore(): Observable<PartnerStore> {
    return this.partnerStores$.pipe(
      take(1),
      switchMap((partnerStores) =>
        this._httpClient
          .post<PartnerStore>('api/apps/member/partner-store/product', {})
          .pipe(
            map((newPartnerStore) => {
              // Update the partnerStores with the new product
              if (!!partnerStores) {
                this.__partnerStores.next([newPartnerStore, ...partnerStores]);
              }

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