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

import { ExcelLog } from '../models/excel-log';
import { ExcelLogPagination } from '../models/excel-log-pagination';

@Injectable({
  providedIn: 'root',
})
export class ExcelLogService {
  // Private
  private __pagination = new BehaviorSubject<ExcelLogPagination | undefined>(
    undefined
  );
  private __excelLog = new BehaviorSubject<ExcelLog | undefined>(undefined);
  private __excelLogs = new BehaviorSubject<ExcelLog[] | undefined>(undefined);

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

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

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

  /**
   * Getter for excelLog
   */
  get excelLog$(): Observable<ExcelLog | undefined> {
    return this.__excelLog.asObservable();
  }

  /**
   * Getter for excelLogs
   */
  get excelLogs$(): Observable<ExcelLog[] | undefined> {
    return this.__excelLogs.asObservable();
  }

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

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

  /**
   * Get product by id
   */
  getExcelLogById(id: string | null): Observable<ExcelLog> {
    return this.__excelLogs.pipe(
      take(1),
      map((excelLogs) => {
        // Find the product
        const excelLog = excelLogs?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__excelLog.next(excelLog);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createExcelLog(): Observable<ExcelLog> {
    return this.excelLogs$.pipe(
      take(1),
      switchMap((excelLogs) =>
        this._httpClient
          .post<ExcelLog>('api/apps/report/excel-log/product', {})
          .pipe(
            map((newExcelLog) => {
              // Update the excelLogs with the new product
              if (!!excelLogs) {
                this.__excelLogs.next([newExcelLog, ...excelLogs]);
              }

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