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

import { Monthly } from '../models/monthly';
import { MonthlyPagination } from '../models/monthly-pagination';

@Injectable({
  providedIn: 'root',
})
export class MonthlyService {
  // Private
  private __pagination = new BehaviorSubject<MonthlyPagination | undefined>(
    undefined
  );
  private __monthly = new BehaviorSubject<Monthly | undefined>(undefined);
  private __monthlys = new BehaviorSubject<Monthly[] | undefined>(undefined);

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

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

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

  /**
   * Getter for monthly
   */
  get monthly$(): Observable<Monthly | undefined> {
    return this.__monthly.asObservable();
  }

  /**
   * Getter for monthlys
   */
  get monthlys$(): Observable<Monthly[] | undefined> {
    return this.__monthlys.asObservable();
  }

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

  /**
   * Get monthlys
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getMonthlys(
    page: number = 0,
    size: number = 10,
    sort: string = 'name',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: MonthlyPagination;
    monthlys: Monthly[];
  }> {
    return this._httpClient
      .get<{
        pagination: MonthlyPagination;
        monthlys: Monthly[];
      }>('api/apps/report/monthly/monthlys', {
        params: {
          page: '' + page,
          size: '' + size,
          sort,
          order,
          search,
        },
      })
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__monthlys.next(response.monthlys);
        })
      );
  }

  /**
   * Get product by id
   */
  getMonthlyById(id: string | null): Observable<Monthly> {
    return this.__monthlys.pipe(
      take(1),
      map((monthlys) => {
        // Find the product
        const monthly = monthlys?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__monthly.next(monthly);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createMonthly(): Observable<Monthly> {
    return this.monthlys$.pipe(
      take(1),
      switchMap((monthlys) =>
        this._httpClient
          .post<Monthly>('api/apps/report/monthly/product', {})
          .pipe(
            map((newMonthly) => {
              // Update the monthlys with the new product
              if (!!monthlys) {
                this.__monthlys.next([newMonthly, ...monthlys]);
              }

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