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

import { DuplicatedSession } from '../models/duplicated-session';
import { DuplicatedSessionPagination } from '../models/duplicated-session-pagination';

@Injectable({
  providedIn: 'root',
})
export class DuplicatedSessionService {
  // Private
  private __pagination = new BehaviorSubject<
    DuplicatedSessionPagination | undefined
  >(undefined);
  private __duplicatedSession = new BehaviorSubject<
    DuplicatedSession | undefined
  >(undefined);
  private __duplicatedSessions = new BehaviorSubject<
    DuplicatedSession[] | undefined
  >(undefined);

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

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

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

  /**
   * Getter for duplicatedSession
   */
  get duplicatedSession$(): Observable<DuplicatedSession | undefined> {
    return this.__duplicatedSession.asObservable();
  }

  /**
   * Getter for duplicatedSessions
   */
  get duplicatedSessions$(): Observable<DuplicatedSession[] | undefined> {
    return this.__duplicatedSessions.asObservable();
  }

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

  /**
   * Get DuplicatedSessions
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getDuplicatedSessions(
    page: number = 0,
    size: number = 10,
    sort: string = 'signinId',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: DuplicatedSessionPagination;
    duplicatedSessions: DuplicatedSession[];
  }> {
    return this._httpClient
      .get<{
        pagination: DuplicatedSessionPagination;
        duplicatedSessions: DuplicatedSession[];
      }>('api/apps/report/duplicated-session/duplicated-sessions', {
        params: {
          page: '' + page,
          size: '' + size,
          sort,
          order,
          search,
        },
      })
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__duplicatedSessions.next(response.duplicatedSessions);
        })
      );
  }

  /**
   * Get product by id
   */
  getDuplicatedSessionById(id: string | null): Observable<DuplicatedSession> {
    return this.__duplicatedSessions.pipe(
      take(1),
      map((duplicatedSessions) => {
        // Find the product
        const duplicatedSession =
          duplicatedSessions?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__duplicatedSession.next(duplicatedSession);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createDuplicatedSession(): Observable<DuplicatedSession> {
    return this.duplicatedSessions$.pipe(
      take(1),
      switchMap((duplicatedSessions) =>
        this._httpClient
          .post<DuplicatedSession>(
            'api/apps/report/duplicated-session/product',
            {}
          )
          .pipe(
            map((newDuplicatedSession) => {
              // Update the duplicatedSessions with the new product
              if (!!duplicatedSessions) {
                this.__duplicatedSessions.next([
                  newDuplicatedSession,
                  ...duplicatedSessions,
                ]);
              }

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