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

import { User } from '../models/user';
import { UserPagination } from '../models/user-pagination';

@Injectable({
  providedIn: 'root',
})
export class UserService {
  // Private
  private __pagination = new BehaviorSubject<UserPagination | undefined>(
    undefined
  );
  private __user = new BehaviorSubject<User | undefined>(undefined);
  private __users = new BehaviorSubject<User[] | undefined>(undefined);

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

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

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

  /**
   * Getter for user
   */
  get user$(): Observable<User | undefined> {
    return this.__user.asObservable();
  }

  /**
   * Getter for users
   */
  get users$(): Observable<User[] | undefined> {
    return this.__users.asObservable();
  }

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

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

  /**
   * Get product by id
   */
  getUserById(id: string | null): Observable<User> {
    return this.__users.pipe(
      take(1),
      map((users) => {
        // Find the product
        const user = users?.find((item) => item.id === id) || undefined;

        // Update the product
        this.__user.next(user);

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

        return of(product);
      })
    );
  }

  /**
   * Create product
   */
  createUser(): Observable<User> {
    return this.users$.pipe(
      take(1),
      switchMap((users) =>
        this._httpClient.post<User>('api/apps/member/user/product', {}).pipe(
          map((newUser) => {
            // Update the users with the new product
            if (!!users) {
              this.__users.next([newUser, ...users]);
            }

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