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

import { UserSession } from '../models/user-session';
import { UserSessionPagination } from '../models/user-session-pagination';

@Injectable({
  providedIn: 'root',
})
export class UserSessionService {
  // Private
  private __pagination = new BehaviorSubject<UserSessionPagination | undefined>(
    undefined
  );
  private __userSession = new BehaviorSubject<UserSession | undefined>(
    undefined
  );
  private __userSessions = new BehaviorSubject<UserSession[] | undefined>(
    undefined
  );

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

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

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

  /**
   * Getter for userSession
   */
  get userSession$(): Observable<UserSession | undefined> {
    return this.__userSession.asObservable();
  }

  /**
   * Getter for userSessions
   */
  get userSessions$(): Observable<UserSession[] | undefined> {
    return this.__userSessions.asObservable();
  }

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

  /**
   * Get UserSessions
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getUserSessions(
    page: number = 0,
    size: number = 10,
    sort: string = 'name',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: UserSessionPagination;
    userSessions: UserSession[];
  }> {
    return this._httpClient
      .get<{
        pagination: UserSessionPagination;
        userSessions: UserSession[];
      }>('api/apps/report/user-session/user-sessions', {
        params: {
          page: '' + page,
          size: '' + size,
          sort,
          order,
          search,
        },
      })
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__userSessions.next(response.userSessions);
        })
      );
  }

  /**
   * Get product by id
   */
  getUserSessionById(id: string | null): Observable<UserSession> {
    return this.__userSessions.pipe(
      take(1),
      map((userSessions) => {
        // Find the product
        const userSession =
          userSessions?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__userSession.next(userSession);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createUserSession(): Observable<UserSession> {
    return this.userSessions$.pipe(
      take(1),
      switchMap((userSessions) =>
        this._httpClient
          .post<UserSession>('api/apps/report/user-session/product', {})
          .pipe(
            map((newUserSession) => {
              // Update the userSessions with the new product
              if (!!userSessions) {
                this.__userSessions.next([newUserSession, ...userSessions]);
              }

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