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

import { PartnerDivision } from '../models/partner-division';
import { PartnerDivisionPagination } from '../models/partner-division-pagination';

@Injectable({
  providedIn: 'root',
})
export class PartnerDivisionService {
  // Private
  private __pagination = new BehaviorSubject<
    PartnerDivisionPagination | undefined
  >(undefined);
  private __partnerDivision = new BehaviorSubject<PartnerDivision | undefined>(
    undefined
  );
  private __partnerDivisions = new BehaviorSubject<
    PartnerDivision[] | undefined
  >(undefined);

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

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

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

  /**
   * Getter for partnerDivision
   */
  get partnerDivision$(): Observable<PartnerDivision | undefined> {
    return this.__partnerDivision.asObservable();
  }

  /**
   * Getter for partnerDivisions
   */
  get partnerDivisions$(): Observable<PartnerDivision[] | undefined> {
    return this.__partnerDivisions.asObservable();
  }

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

  /**
   * Get partnerDivisions
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getPartnerDivisions(
    page: number = 0,
    size: number = 10,
    sort: string = 'name',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: PartnerDivisionPagination;
    partnerDivisions: PartnerDivision[];
  }> {
    return this._httpClient
      .get<{
        pagination: PartnerDivisionPagination;
        partnerDivisions: PartnerDivision[];
      }>('api/apps/member/partner-division/partner-divisions', {
        params: {
          page: '' + page,
          size: '' + size,
          sort,
          order,
          search,
        },
      })
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__partnerDivisions.next(response.partnerDivisions);
        })
      );
  }

  /**
   * Get product by id
   */
  getPartnerDivisionById(id: string | null): Observable<PartnerDivision> {
    return this.__partnerDivisions.pipe(
      take(1),
      map((partnerDivisions) => {
        // Find the product
        const partnerDivision =
          partnerDivisions?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__partnerDivision.next(partnerDivision);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createPartnerDivision(): Observable<PartnerDivision> {
    return this.partnerDivisions$.pipe(
      take(1),
      switchMap((partnerDivisions) =>
        this._httpClient
          .post<PartnerDivision>('api/apps/member/partner-division/product', {})
          .pipe(
            map((newPartnerDivision) => {
              // Update the partnerDivisions with the new product
              if (!!partnerDivisions) {
                this.__partnerDivisions.next([
                  newPartnerDivision,
                  ...partnerDivisions,
                ]);
              }

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