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

import { CustomerTemplate } from '../models/ customer-template';
import { CustomerTemplatePagination } from '../models/customer-template-pagination';

@Injectable({
  providedIn: 'root',
})
export class CustomerTemplateService {
  // Private
  private __pagination = new BehaviorSubject<
    CustomerTemplatePagination | undefined
  >(undefined);
  private __customerTemplate = new BehaviorSubject<
    CustomerTemplate | undefined
  >(undefined);
  private __customerTemplates = new BehaviorSubject<
    CustomerTemplate[] | undefined
  >(undefined);

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

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

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

  /**
   * Getter for customerTemplate
   */
  get customerTemplate$(): Observable<CustomerTemplate | undefined> {
    return this.__customerTemplate.asObservable();
  }

  /**
   * Getter for customerTemplates
   */
  get customerTemplates$(): Observable<CustomerTemplate[] | undefined> {
    return this.__customerTemplates.asObservable();
  }

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

  /**
   * Get CustomerTemplates
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getCustomerTemplates(
    page: number = 0,
    size: number = 10,
    sort: string = 'name',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: CustomerTemplatePagination;
    customerTemplates: CustomerTemplate[];
  }> {
    return this._httpClient
      .get<{
        pagination: CustomerTemplatePagination;
        customerTemplates: CustomerTemplate[];
      }>('api/apps/board/customer-template/customer-templates', {
        params: {
          page: '' + page,
          size: '' + size,
          sort,
          order,
          search,
        },
      })
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__customerTemplates.next(response.customerTemplates);
        })
      );
  }

  /**
   * Get product by id
   */
  getCustomerTemplateById(id: string | null): Observable<CustomerTemplate> {
    return this.__customerTemplates.pipe(
      take(1),
      map((customerTemplates) => {
        // Find the product
        const customerTemplate =
          customerTemplates?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__customerTemplate.next(customerTemplate);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createCustomerTemplate(): Observable<CustomerTemplate> {
    return this.customerTemplates$.pipe(
      take(1),
      switchMap((customerTemplates) =>
        this._httpClient
          .post<CustomerTemplate>(
            'api/apps/board/customer-template/product',
            {}
          )
          .pipe(
            map((newCustomerTemplate) => {
              // Update the customerTemplates with the new product
              if (!!customerTemplates) {
                this.__customerTemplates.next([
                  newCustomerTemplate,
                  ...customerTemplates,
                ]);
              }

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