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

import { Unconnected } from '../models/unconnected';
import { UnconnectedPagination } from '../models/unconnected-pagination';

@Injectable({
  providedIn: 'root',
})
export class UnconnectedService {
  // Private
  private __pagination = new BehaviorSubject<UnconnectedPagination | undefined>(
    undefined
  );
  private __unconnected = new BehaviorSubject<Unconnected | undefined>(
    undefined
  );
  private __unconnecteds = new BehaviorSubject<Unconnected[] | undefined>(
    undefined
  );

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

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

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

  /**
   * Getter for unconnected
   */
  get unconnected$(): Observable<Unconnected | undefined> {
    return this.__unconnected.asObservable();
  }

  /**
   * Getter for unconnecteds
   */
  get unconnecteds$(): Observable<Unconnected[] | undefined> {
    return this.__unconnecteds.asObservable();
  }

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

  /**
   * Get unconnecteds
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getUnconnecteds(
    page: number = 0,
    size: number = 10,
    sort: string = 'name',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: UnconnectedPagination;
    unconnecteds: Unconnected[];
  }> {
    return this._httpClient
      .get<{ pagination: UnconnectedPagination; unconnecteds: Unconnected[] }>(
        'api/apps/member/unconnected/unconnecteds',
        {
          params: {
            page: '' + page,
            size: '' + size,
            sort,
            order,
            search,
          },
        }
      )
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__unconnecteds.next(response.unconnecteds);
        })
      );
  }

  /**
   * Get product by id
   */
  getUnconnectedById(id: string | null): Observable<Unconnected> {
    return this.__unconnecteds.pipe(
      take(1),
      map((unconnecteds) => {
        // Find the product
        const unconnected =
          unconnecteds?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__unconnected.next(unconnected);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createUnconnected(): Observable<Unconnected> {
    return this.unconnecteds$.pipe(
      take(1),
      switchMap((unconnecteds) =>
        this._httpClient
          .post<Unconnected>('api/apps/member/unconnected/product', {})
          .pipe(
            map((newUnconnected) => {
              // Update the unconnecteds with the new product
              if (!!unconnecteds) {
                this.__unconnecteds.next([newUnconnected, ...unconnecteds]);
              }

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