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

import { Loosing } from '../models/loosing';
import { LoosingPagination } from '../models/loosing-pagination';
import { LoosingReport } from '../models/loosing-report';

@Injectable({
  providedIn: 'root',
})
export class LoosingService {
  // Private
  private __pagination = new BehaviorSubject<LoosingPagination | undefined>(
    undefined
  );
  private __loosing = new BehaviorSubject<LoosingReport[] | undefined>(
    undefined
  );
  private __loosings = new BehaviorSubject<Loosing[] | undefined>(undefined);

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

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

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

  /**
   * Getter for loosing
   */
  get loosing$(): Observable<LoosingReport[] | undefined> {
    return this.__loosing.asObservable();
  }

  /**
   * Getter for loosings
   */
  get loosings$(): Observable<Loosing[] | undefined> {
    return this.__loosings.asObservable();
  }

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

  /**
   * Get Loosings
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getLoosings(
    page: number = 0,
    size: number = 10,
    sort: string = 'name',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: LoosingPagination;
    loosings: Loosing[];
  }> {
    return this._httpClient
      .get<{
        pagination: LoosingPagination;
        loosings: Loosing[];
      }>('api/apps/report/loosing/loosings', {
        params: {
          page: '' + page,
          size: '' + size,
          sort,
          order,
          search,
        },
      })
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__loosings.next(response.loosings);
        })
      );
  }

  /**
   * Get product by id
   */
  getLoosingById(
    id: string = '1',
    type: string = '1'
  ): Observable<LoosingReport[]> {
    return this._httpClient
      .get<LoosingReport[]>('api/apps/report/loosing/loosing', {
        params: { id, type },
      })
      .pipe(
        tap((response: LoosingReport[]) => {
          this.__loosing.next(response);
        })
      );
  }

  /**
   * Create product
   */
  createLoosing(): Observable<Loosing> {
    return this.loosings$.pipe(
      take(1),
      switchMap((loosings) =>
        this._httpClient
          .post<Loosing>('api/apps/report/loosing/product', {})
          .pipe(
            map((newLoosing) => {
              // Update the loosings with the new product
              if (!!loosings) {
                this.__loosings.next([newLoosing, ...loosings]);
              }

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