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

import { PartnerMainoffice } from '../models/partner-mainoffice';
import { PartnerMainofficePagination } from '../models/partner-mainoffice-pagination';

@Injectable({
  providedIn: 'root',
})
export class PartnerMainofficeService {
  // Private
  private __pagination = new BehaviorSubject<
    PartnerMainofficePagination | undefined
  >(undefined);
  private __partnerMainoffice = new BehaviorSubject<
    PartnerMainoffice | undefined
  >(undefined);
  private __partnerMainoffices = new BehaviorSubject<
    PartnerMainoffice[] | undefined
  >(undefined);

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

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

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

  /**
   * Getter for partnerMainoffice
   */
  get partnerMainoffice$(): Observable<PartnerMainoffice | undefined> {
    return this.__partnerMainoffice.asObservable();
  }

  /**
   * Getter for partnerMainoffices
   */
  get partnerMainoffices$(): Observable<PartnerMainoffice[] | undefined> {
    return this.__partnerMainoffices.asObservable();
  }

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

  /**
   * Get partnerMainoffices
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getPartnerMainoffices(
    page: number = 0,
    size: number = 10,
    sort: string = 'name',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: PartnerMainofficePagination;
    partnerMainoffices: PartnerMainoffice[];
  }> {
    return this._httpClient
      .get<{
        pagination: PartnerMainofficePagination;
        partnerMainoffices: PartnerMainoffice[];
      }>('api/apps/member/partner-mainoffice/partner-mainoffices', {
        params: {
          page: '' + page,
          size: '' + size,
          sort,
          order,
          search,
        },
      })
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__partnerMainoffices.next(response.partnerMainoffices);
        })
      );
  }

  /**
   * Get product by id
   */
  getPartnerMainofficeById(id: string | null): Observable<PartnerMainoffice> {
    return this.__partnerMainoffices.pipe(
      take(1),
      map((partnerMainoffices) => {
        // Find the product
        const partnerMainoffice =
          partnerMainoffices?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__partnerMainoffice.next(partnerMainoffice);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createPartnerMainoffice(): Observable<PartnerMainoffice> {
    return this.partnerMainoffices$.pipe(
      take(1),
      switchMap((partnerMainoffices) =>
        this._httpClient
          .post<PartnerMainoffice>(
            'api/apps/member/partner-mainoffice/product',
            {}
          )
          .pipe(
            map((newPartnerMainoffice) => {
              // Update the partnerMainoffices with the new product
              if (!!partnerMainoffices) {
                this.__partnerMainoffices.next([
                  newPartnerMainoffice,
                  ...partnerMainoffices,
                ]);
              }

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