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

import { PartnerBranch } from '../models/partner-branch';
import { PartnerBranchPagination } from '../models/partner-branch-pagination';

@Injectable({
  providedIn: 'root',
})
export class PartnerBranchService {
  // Private
  private __pagination = new BehaviorSubject<
    PartnerBranchPagination | undefined
  >(undefined);
  private __partnerBranch = new BehaviorSubject<PartnerBranch | undefined>(
    undefined
  );
  private __partnerBranchs = new BehaviorSubject<PartnerBranch[] | undefined>(
    undefined
  );

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

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

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

  /**
   * Getter for partnerBranch
   */
  get partnerBranch$(): Observable<PartnerBranch | undefined> {
    return this.__partnerBranch.asObservable();
  }

  /**
   * Getter for partnerBranchs
   */
  get partnerBranchs$(): Observable<PartnerBranch[] | undefined> {
    return this.__partnerBranchs.asObservable();
  }

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

  /**
   * Get partnerBranchs
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getPartnerBranchs(
    page: number = 0,
    size: number = 10,
    sort: string = 'name',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: PartnerBranchPagination;
    partnerBranchs: PartnerBranch[];
  }> {
    return this._httpClient
      .get<{
        pagination: PartnerBranchPagination;
        partnerBranchs: PartnerBranch[];
      }>('api/apps/member/partner-branch/partner-branchs', {
        params: {
          page: '' + page,
          size: '' + size,
          sort,
          order,
          search,
        },
      })
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__partnerBranchs.next(response.partnerBranchs);
        })
      );
  }

  /**
   * Get product by id
   */
  getPartnerBranchById(id: string | null): Observable<PartnerBranch> {
    return this.__partnerBranchs.pipe(
      take(1),
      map((partnerBranchs) => {
        // Find the product
        const partnerBranch =
          partnerBranchs?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__partnerBranch.next(partnerBranch);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createPartnerBranch(): Observable<PartnerBranch> {
    return this.partnerBranchs$.pipe(
      take(1),
      switchMap((partnerBranchs) =>
        this._httpClient
          .post<PartnerBranch>('api/apps/member/partner-branch/product', {})
          .pipe(
            map((newPartnerBranch) => {
              // Update the partnerBranchs with the new product
              if (!!partnerBranchs) {
                this.__partnerBranchs.next([
                  newPartnerBranch,
                  ...partnerBranchs,
                ]);
              }

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