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

import { Popup } from '../models/popup';
import { PopupPagination } from '../models/popup-pagination';

@Injectable({
  providedIn: 'root',
})
export class PopupService {
  // Private
  private __pagination = new BehaviorSubject<PopupPagination | undefined>(
    undefined
  );
  private __popup = new BehaviorSubject<Popup | undefined>(undefined);
  private __popups = new BehaviorSubject<Popup[] | undefined>(undefined);

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

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

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

  /**
   * Getter for popup
   */
  get popup$(): Observable<Popup | undefined> {
    return this.__popup.asObservable();
  }

  /**
   * Getter for popups
   */
  get popups$(): Observable<Popup[] | undefined> {
    return this.__popups.asObservable();
  }

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

  /**
   * Get Popups
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getPopups(
    page: number = 0,
    size: number = 10,
    sort: string = 'name',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: PopupPagination;
    popups: Popup[];
  }> {
    return this._httpClient
      .get<{
        pagination: PopupPagination;
        popups: Popup[];
      }>('api/apps/board/popup/popups', {
        params: {
          page: '' + page,
          size: '' + size,
          sort,
          order,
          search,
        },
      })
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__popups.next(response.popups);
        })
      );
  }

  /**
   * Get product by id
   */
  getPopupById(id: string | null): Observable<Popup> {
    return this.__popups.pipe(
      take(1),
      map((popups) => {
        // Find the product
        const popup = popups?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__popup.next(popup);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createPopup(): Observable<Popup> {
    return this.popups$.pipe(
      take(1),
      switchMap((popups) =>
        this._httpClient.post<Popup>('api/apps/board/popup/product', {}).pipe(
          map((newPopup) => {
            // Update the popups with the new product
            if (!!popups) {
              this.__popups.next([newPopup, ...popups]);
            }

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