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

import { ModificationLog } from '../models/modification-log';
import { ModificationLogPagination } from '../models/modification-log-pagination';

@Injectable({
  providedIn: 'root',
})
export class ModificationLogService {
  // Private
  private __pagination = new BehaviorSubject<
    ModificationLogPagination | undefined
  >(undefined);
  private __modificationLog = new BehaviorSubject<ModificationLog | undefined>(
    undefined
  );
  private __modificationLogs = new BehaviorSubject<
    ModificationLog[] | undefined
  >(undefined);

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

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

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

  /**
   * Getter for modificationLog
   */
  get modificationLog$(): Observable<ModificationLog | undefined> {
    return this.__modificationLog.asObservable();
  }

  /**
   * Getter for modificationLogs
   */
  get modificationLogs$(): Observable<ModificationLog[] | undefined> {
    return this.__modificationLogs.asObservable();
  }

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

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

  /**
   * Get product by id
   */
  getModificationLogById(id: string | null): Observable<ModificationLog> {
    return this.__modificationLogs.pipe(
      take(1),
      map((modificationLogs) => {
        // Find the product
        const modificationLog =
          modificationLogs?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__modificationLog.next(modificationLog);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createModificationLog(): Observable<ModificationLog> {
    return this.modificationLogs$.pipe(
      take(1),
      switchMap((modificationLogs) =>
        this._httpClient
          .post<ModificationLog>('api/apps/report/modification-log/product', {})
          .pipe(
            map((newModificationLog) => {
              // Update the modificationLogs with the new product
              if (!!modificationLogs) {
                this.__modificationLogs.next([
                  newModificationLog,
                  ...modificationLogs,
                ]);
              }

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