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

import { Customer } from '../models/customer';
import { CustomerPagination } from '../models/customer-pagination';

@Injectable({
  providedIn: 'root',
})
export class CustomerService {
  // Private
  private __pagination = new BehaviorSubject<CustomerPagination | undefined>(
    undefined
  );
  private __customer = new BehaviorSubject<Customer | undefined>(undefined);
  private __customers = new BehaviorSubject<Customer[] | undefined>(undefined);

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

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

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

  /**
   * Getter for customer
   */
  get customer$(): Observable<Customer | undefined> {
    return this.__customer.asObservable();
  }

  /**
   * Getter for customers
   */
  get customers$(): Observable<Customer[] | undefined> {
    return this.__customers.asObservable();
  }

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

  /**
   * Get customers
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getCustomers(
    page: number = 0,
    size: number = 10,
    sort: string = 'name',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: CustomerPagination;
    customers: Customer[];
  }> {
    return this._httpClient
      .get<{
        pagination: CustomerPagination;
        customers: Customer[];
      }>('api/apps/board/customer/customers', {
        params: {
          page: '' + page,
          size: '' + size,
          sort,
          order,
          search,
        },
      })
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__customers.next(response.customers);
        })
      );
  }

  /**
   * Get product by id
   */
  getCustomerById(id: string | null): Observable<Customer> {
    return this.__customers.pipe(
      take(1),
      map((customers) => {
        // Find the product
        const customer = customers?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__customer.next(customer);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createCustomer(): Observable<Customer> {
    return this.customers$.pipe(
      take(1),
      switchMap((customers) =>
        this._httpClient
          .post<Customer>('api/apps/board/customer/product', {})
          .pipe(
            map((newCustomer) => {
              // Update the customers with the new product
              if (!!customers) {
                this.__customers.next([newCustomer, ...customers]);
              }

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