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

import { CompLog } from '../models/comp-log';
import { CompLogPagination } from '../models/comp-log-pagination';

@Injectable({
  providedIn: 'root',
})
export class CompLogService {
  // Private
  private __pagination = new BehaviorSubject<CompLogPagination | undefined>(
    undefined
  );
  private __compLog = new BehaviorSubject<CompLog | undefined>(undefined);
  private __compLogs = new BehaviorSubject<CompLog[] | undefined>(undefined);

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

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

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

  /**
   * Getter for compLog
   */
  get compLog$(): Observable<CompLog | undefined> {
    return this.__compLog.asObservable();
  }

  /**
   * Getter for compLogs
   */
  get compLogs$(): Observable<CompLog[] | undefined> {
    return this.__compLogs.asObservable();
  }

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

  /**
   * Get compLogs
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getCompLogs(
    page: number = 0,
    size: number = 10,
    sort: string = 'name',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: CompLogPagination;
    compLogs: CompLog[];
  }> {
    return this._httpClient
      .get<{
        pagination: CompLogPagination;
        compLogs: CompLog[];
      }>('api/apps/report/comp-log/comp-logs', {
        params: {
          page: '' + page,
          size: '' + size,
          sort,
          order,
          search,
        },
      })
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__compLogs.next(response.compLogs);
        })
      );
  }

  /**
   * Get product by id
   */
  getCompLogById(id: string | null): Observable<CompLog> {
    return this.__compLogs.pipe(
      take(1),
      map((compLogs) => {
        // Find the product
        const compLog = compLogs?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__compLog.next(compLog);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createCompLog(): Observable<CompLog> {
    return this.compLogs$.pipe(
      take(1),
      switchMap((compLogs) =>
        this._httpClient
          .post<CompLog>('api/apps/report/comp-log/product', {})
          .pipe(
            map((newCompLog) => {
              // Update the compLogs with the new product
              if (!!compLogs) {
                this.__compLogs.next([newCompLog, ...compLogs]);
              }

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