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

import { NoticeOneline } from '../models/notice-oneline';
import { NoticeOnelinePagination } from '../models/notice-oneline-pagination';

@Injectable({
  providedIn: 'root',
})
export class NoticeOnelineService {
  // Private
  private __pagination = new BehaviorSubject<
    NoticeOnelinePagination | undefined
  >(undefined);
  private __noticeOneline = new BehaviorSubject<NoticeOneline | undefined>(
    undefined
  );
  private __noticeOnelines = new BehaviorSubject<NoticeOneline[] | undefined>(
    undefined
  );

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

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

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

  /**
   * Getter for noticeOneline
   */
  get noticeOneline$(): Observable<NoticeOneline | undefined> {
    return this.__noticeOneline.asObservable();
  }

  /**
   * Getter for noticeOnelines
   */
  get noticeOnelines$(): Observable<NoticeOneline[] | undefined> {
    return this.__noticeOnelines.asObservable();
  }

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

  /**
   * Get NoticeOnelines
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getNoticeOnelines(
    page: number = 0,
    size: number = 10,
    sort: string = 'name',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: NoticeOnelinePagination;
    noticeOnelines: NoticeOneline[];
  }> {
    return this._httpClient
      .get<{
        pagination: NoticeOnelinePagination;
        noticeOnelines: NoticeOneline[];
      }>('api/apps/board/notice-oneline/notice-onelines', {
        params: {
          page: '' + page,
          size: '' + size,
          sort,
          order,
          search,
        },
      })
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__noticeOnelines.next(response.noticeOnelines);
        })
      );
  }

  /**
   * Get product by id
   */
  getNoticeOnelineById(title: string | null): Observable<NoticeOneline> {
    return this.__noticeOnelines.pipe(
      take(1),
      map((noticeOnelines) => {
        // Find the product
        const noticeOneline =
          noticeOnelines?.find((item) => !!item && !!item.title === !!title) ||
          undefined;

        // Update the product
        this.__noticeOneline.next(noticeOneline);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createNoticeOneline(): Observable<NoticeOneline> {
    return this.noticeOnelines$.pipe(
      take(1),
      switchMap((noticeOnelines) =>
        this._httpClient
          .post<NoticeOneline>('api/apps/board/notice-oneline/product', {})
          .pipe(
            map((newNoticeOneline) => {
              // Update the noticeOnelines with the new product
              if (!!noticeOnelines) {
                this.__noticeOnelines.next([
                  newNoticeOneline,
                  ...noticeOnelines,
                ]);
              }

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