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

import { MoneyLog } from '../models/money-log';
import { MoneyLogPagination } from '../models/money-log-pagination';

@Injectable({
  providedIn: 'root',
})
export class MoneyLogService {
  // Private
  private __pagination = new BehaviorSubject<MoneyLogPagination | undefined>(
    undefined
  );
  private __moneyLog = new BehaviorSubject<MoneyLog | undefined>(undefined);
  private __moneyLogs = new BehaviorSubject<MoneyLog[] | undefined>(undefined);

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

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

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

  /**
   * Getter for moneyLog
   */
  get moneyLog$(): Observable<MoneyLog | undefined> {
    return this.__moneyLog.asObservable();
  }

  /**
   * Getter for moneyLogs
   */
  get moneyLogs$(): Observable<MoneyLog[] | undefined> {
    return this.__moneyLogs.asObservable();
  }

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

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

  /**
   * Get product by id
   */
  getMoneyLogById(id: string | null): Observable<MoneyLog> {
    return this.__moneyLogs.pipe(
      take(1),
      map((moneyLogs) => {
        // Find the product
        const moneyLog = moneyLogs?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__moneyLog.next(moneyLog);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createMoneyLog(): Observable<MoneyLog> {
    return this.moneyLogs$.pipe(
      take(1),
      switchMap((moneyLogs) =>
        this._httpClient
          .post<MoneyLog>('api/apps/report/money-log/product', {})
          .pipe(
            map((newMoneyLog) => {
              // Update the moneyLogs with the new product
              if (!!moneyLogs) {
                this.__moneyLogs.next([newMoneyLog, ...moneyLogs]);
              }

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