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

import { Notice } from '../models/notice';
import { NoticePagination } from '../models/notice-pagination';

@Injectable({
  providedIn: 'root',
})
export class NoticeService {
  // Private
  private __pagination = new BehaviorSubject<NoticePagination | undefined>(
    undefined
  );
  private __notice = new BehaviorSubject<Notice | undefined>(undefined);
  private __notices = new BehaviorSubject<Notice[] | undefined>(undefined);

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

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

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

  /**
   * Getter for notice
   */
  get notice$(): Observable<Notice | undefined> {
    return this.__notice.asObservable();
  }

  /**
   * Getter for notices
   */
  get notices$(): Observable<Notice[] | undefined> {
    return this.__notices.asObservable();
  }

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

  /**
   * Get Notices
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getNotices(
    page: number = 0,
    size: number = 10,
    sort: string = 'name',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: NoticePagination;
    notices: Notice[];
  }> {
    return this._httpClient
      .get<{
        pagination: NoticePagination;
        notices: Notice[];
      }>('api/apps/board/notice/notices', {
        params: {
          page: '' + page,
          size: '' + size,
          sort,
          order,
          search,
        },
      })
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__notices.next(response.notices);
        })
      );
  }

  /**
   * Get product by id
   */
  getNoticeById(id: string | null): Observable<Notice> {
    return this.__notices.pipe(
      take(1),
      map((notices) => {
        // Find the product
        const notice = notices?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__notice.next(notice);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createNotice(): Observable<Notice> {
    return this.notices$.pipe(
      take(1),
      switchMap((notices) =>
        this._httpClient.post<Notice>('api/apps/board/notice/product', {}).pipe(
          map((newNotice) => {
            // Update the notices with the new product
            if (!!notices) {
              this.__notices.next([newNotice, ...notices]);
            }

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