import { Injectable, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { User } from 'src/modules/user/model/user.model';
import { API_BASE_URL } from 'src/modules/common/type/injection-token.type';
import { Page } from 'src/modules/common/data/model/page';
import { map } from 'rxjs/operators';

@Injectable()
export class UserService {
  constructor(
    @Inject(API_BASE_URL) private apiBaseUrl: string,
    private httpClient: HttpClient
  ) {}

  public getAllUsers(): Observable<Page<User>> {
    return this.httpClient.get<Page<User>>(`${this.apiBaseUrl}/users`, {});
  }

  public getUser(id: number): Observable<User> {
    return this.httpClient.get<User>(`${this.apiBaseUrl}/users/${id}`, {});
  }

  public updateUser(
    id: number,
    newUser: User,
    newPassword: string
  ): Observable<User> {
    const username = newUser.username;
    const password = newPassword;
    const email = newUser.email;
    const phone = newUser.phone;
    const descriptions = newUser.descriptions;
    const nickname = newUser.nickname;

    return this.httpClient
      .put<any>(`${this.apiBaseUrl}/users/${id}`, {
        username,
        nickname,
        email,
        password,
        descriptions,
        phone
      })
      .pipe(
        map(res => {
          console.log('update response: ' + res);
          return res;
        })
      );
  }
}
