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

import { Daily } from '../models/daily';
import { DailyPagination } from '../models/daily-pagination';

@Injectable({
  providedIn: 'root',
})
export class DailyService {
  // Private
  private __pagination = new BehaviorSubject<DailyPagination | undefined>(
    undefined
  );
  private __daily = new BehaviorSubject<Daily | undefined>(undefined);
  private __dailys = new BehaviorSubject<Daily[] | undefined>(undefined);

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

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

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

  /**
   * Getter for daily
   */
  get daily$(): Observable<Daily | undefined> {
    return this.__daily.asObservable();
  }

  /**
   * Getter for dailys
   */
  get dailys$(): Observable<Daily[] | undefined> {
    return this.__dailys.asObservable();
  }

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

  /**
   * Get Dailys
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getDailys(
    page: number = 0,
    size: number = 10,
    sort: string = 'name',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: DailyPagination;
    dailys: Daily[];
  }> {
    return this._httpClient
      .get<{
        pagination: DailyPagination;
        dailys: Daily[];
      }>('api/apps/report/daily/dailys', {
        params: {
          page: '' + page,
          size: '' + size,
          sort,
          order,
          search,
        },
      })
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__dailys.next(response.dailys);
        })
      );
  }

  /**
   * Get product by id
   */
  getDailyById(id: string | null): Observable<Daily> {
    return this.__dailys.pipe(
      take(1),
      map((dailys) => {
        // Find the product
        const daily = dailys?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__daily.next(daily);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createDaily(): Observable<Daily> {
    return this.dailys$.pipe(
      take(1),
      switchMap((dailys) =>
        this._httpClient.post<Daily>('api/apps/report/daily/product', {}).pipe(
          map((newDaily) => {
            // Update the dailys with the new product
            if (!!dailys) {
              this.__dailys.next([newDaily, ...dailys]);
            }

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