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

import { PartnerOffice } from '../models/partner-office';
import { PartnerOfficePagination } from '../models/partner-office-pagination';

@Injectable({
  providedIn: 'root',
})
export class PartnerOfficeService {
  // Private
  private __pagination = new BehaviorSubject<
    PartnerOfficePagination | undefined
  >(undefined);
  private __partnerOffice = new BehaviorSubject<PartnerOffice | undefined>(
    undefined
  );
  private __partnerOffices = new BehaviorSubject<PartnerOffice[] | undefined>(
    undefined
  );

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

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

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

  /**
   * Getter for partnerOffice
   */
  get partnerOffice$(): Observable<PartnerOffice | undefined> {
    return this.__partnerOffice.asObservable();
  }

  /**
   * Getter for partnerOffices
   */
  get partnerOffices$(): Observable<PartnerOffice[] | undefined> {
    return this.__partnerOffices.asObservable();
  }

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

  /**
   * Get partnerOffices
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getPartnerOffices(
    page: number = 0,
    size: number = 10,
    sort: string = 'name',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: PartnerOfficePagination;
    partnerOffices: PartnerOffice[];
  }> {
    return this._httpClient
      .get<{
        pagination: PartnerOfficePagination;
        partnerOffices: PartnerOffice[];
      }>('api/apps/member/partner-office/partner-offices', {
        params: {
          page: '' + page,
          size: '' + size,
          sort,
          order,
          search,
        },
      })
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__partnerOffices.next(response.partnerOffices);
        })
      );
  }

  /**
   * Get product by id
   */
  getPartnerOfficeById(id: string | null): Observable<PartnerOffice> {
    return this.__partnerOffices.pipe(
      take(1),
      map((partnerOffices) => {
        // Find the product
        const partnerOffice =
          partnerOffices?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__partnerOffice.next(partnerOffice);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createPartnerOffice(): Observable<PartnerOffice> {
    return this.partnerOffices$.pipe(
      take(1),
      switchMap((partnerOffices) =>
        this._httpClient
          .post<PartnerOffice>('api/apps/member/partner-office/product', {})
          .pipe(
            map((newPartnerOffice) => {
              // Update the partnerOffices with the new product
              if (!!partnerOffices) {
                this.__partnerOffices.next([
                  newPartnerOffice,
                  ...partnerOffices,
                ]);
              }

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