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

import { CurrentUser } from '../models/current-user';
import { CurrentUserPagination } from '../models/current-user-pagination';

@Injectable({
  providedIn: 'root',
})
export class CurrentUserService {
  // Private
  private __pagination = new BehaviorSubject<CurrentUserPagination | undefined>(
    undefined
  );
  private __currentUser = new BehaviorSubject<CurrentUser | undefined>(
    undefined
  );
  private __currentUsers = new BehaviorSubject<CurrentUser[] | undefined>(
    undefined
  );

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

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

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

  /**
   * Getter for currentUser
   */
  get currentUser$(): Observable<CurrentUser | undefined> {
    return this.__currentUser.asObservable();
  }

  /**
   * Getter for currentUsers
   */
  get currentUsers$(): Observable<CurrentUser[] | undefined> {
    return this.__currentUsers.asObservable();
  }

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

  /**
   * Get currentUsers
   *
   *
   * @param page
   * @param size
   * @param sort
   * @param order
   * @param search
   */
  getCurrentUsers(
    page: number = 0,
    size: number = 10,
    sort: string = 'name',
    order: 'asc' | 'desc' | '' = 'asc',
    search: string = ''
  ): Observable<{
    pagination: CurrentUserPagination;
    currentUsers: CurrentUser[];
  }> {
    return this._httpClient
      .get<{ pagination: CurrentUserPagination; currentUsers: CurrentUser[] }>(
        'api/apps/member/current-user/current-users',
        {
          params: {
            page: '' + page,
            size: '' + size,
            sort,
            order,
            search,
          },
        }
      )
      .pipe(
        tap((response) => {
          this.__pagination.next(response.pagination);
          this.__currentUsers.next(response.currentUsers);
        })
      );
  }

  /**
   * Get product by id
   */
  getCurrentUserById(id: string | null): Observable<CurrentUser> {
    return this.__currentUsers.pipe(
      take(1),
      map((currentUsers) => {
        // Find the product
        const currentUser =
          currentUsers?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__currentUser.next(currentUser);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createCurrentUser(): Observable<CurrentUser> {
    return this.currentUsers$.pipe(
      take(1),
      switchMap((currentUsers) =>
        this._httpClient
          .post<CurrentUser>('api/apps/member/currentUser/product', {})
          .pipe(
            map((newCurrentUser) => {
              // Update the currentUsers with the new product
              if (!!currentUsers) {
                this.__currentUsers.next([newCurrentUser, ...currentUsers]);
              }

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