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

import { AdminSession } from '../models/admin-session';
import { AdminSessionPagination } from '../models/admin-session-pagination';

@Injectable({
  providedIn: 'root',
})
export class AdminSessionService {
  // Private
  private __pagination = new BehaviorSubject<
    AdminSessionPagination | undefined
  >(undefined);
  private __adminSession = new BehaviorSubject<AdminSession | undefined>(
    undefined
  );
  private __adminSessions = new BehaviorSubject<AdminSession[] | undefined>(
    undefined
  );

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

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

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

  /**
   * Getter for adminSession
   */
  get adminSession$(): Observable<AdminSession | undefined> {
    return this.__adminSession.asObservable();
  }

  /**
   * Getter for adminSessions
   */
  get adminSessions$(): Observable<AdminSession[] | undefined> {
    return this.__adminSessions.asObservable();
  }

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

  /**
   * Get AdminSessions
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getAdminSessions(
    page: number = 0,
    size: number = 10,
    sort: string = 'name',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: AdminSessionPagination;
    adminSessions: AdminSession[];
  }> {
    return this._httpClient
      .get<{
        pagination: AdminSessionPagination;
        adminSessions: AdminSession[];
      }>('api/apps/report/admin-session/admin-sessions', {
        params: {
          page: '' + page,
          size: '' + size,
          sort,
          order,
          search,
        },
      })
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__adminSessions.next(response.adminSessions);
        })
      );
  }

  /**
   * Get product by id
   */
  getAdminSessionById(id: string | null): Observable<AdminSession> {
    return this.__adminSessions.pipe(
      take(1),
      map((adminSessions) => {
        // Find the product
        const adminSession =
          adminSessions?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__adminSession.next(adminSession);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createAdminSession(): Observable<AdminSession> {
    return this.adminSessions$.pipe(
      take(1),
      switchMap((adminSessions) =>
        this._httpClient
          .post<AdminSession>('api/apps/report/admin-session/product', {})
          .pipe(
            map((newAdminSession) => {
              // Update the adminSessions with the new product
              if (!!adminSessions) {
                this.__adminSessions.next([newAdminSession, ...adminSessions]);
              }

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