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

import { Message } from '../models/message';
import { MessagePagination } from '../models/message-pagination';

@Injectable({
  providedIn: 'root',
})
export class MessageService {
  // Private
  private __pagination = new BehaviorSubject<MessagePagination | undefined>(
    undefined
  );
  private __message = new BehaviorSubject<Message | undefined>(undefined);
  private __messages = new BehaviorSubject<Message[] | undefined>(undefined);

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

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

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

  /**
   * Getter for message
   */
  get message$(): Observable<Message | undefined> {
    return this.__message.asObservable();
  }

  /**
   * Getter for messages
   */
  get messages$(): Observable<Message[] | undefined> {
    return this.__messages.asObservable();
  }

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

  /**
   * Get Messages
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getMessages(
    page: number = 0,
    size: number = 10,
    sort: string = 'name',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: MessagePagination;
    messages: Message[];
  }> {
    return this._httpClient
      .get<{
        pagination: MessagePagination;
        messages: Message[];
      }>('api/apps/board/message/messages', {
        params: {
          page: '' + page,
          size: '' + size,
          sort,
          order,
          search,
        },
      })
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__messages.next(response.messages);
        })
      );
  }

  /**
   * Get product by id
   */
  getMessageById(id: string | null): Observable<Message> {
    return this.__messages.pipe(
      take(1),
      map((messages) => {
        // Find the product
        const message = messages?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__message.next(message);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createMessage(): Observable<Message> {
    return this.messages$.pipe(
      take(1),
      switchMap((messages) =>
        this._httpClient
          .post<Message>('api/apps/board/message/product', {})
          .pipe(
            map((newMessage) => {
              // Update the messages with the new product
              if (!!messages) {
                this.__messages.next([newMessage, ...messages]);
              }

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