import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from '../../environments/environment.prod';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class UsersService {

  constructor( private httpClient: HttpClient ) { }

  getMe() {
    return this.httpClient.get(`${environment.apiVersionPath}/users/me`);
  }

  getUserById(userId) {
    return this.httpClient.get(`${environment.apiVersionPath}/users/${userId}`);
  }
  
  getUsers(sort: Boolean = false) : Observable<any> {
    return this.httpClient.get(`${environment.apiVersionPath}/users`).pipe(map((users:any)=>{
      if (sort){
        users.results = users.results.sort(function(a, b){return a.displayName.localeCompare(b.displayName);});
      }
      return users;
    }));
  }

  updateUser(userId, patchData): Observable<any> {
    return this.httpClient.put(`${environment.apiVersionPath}/users/${userId}`, patchData);
  }

  getNotifications(): Observable<any> {
    let params = new HttpParams();  
    params = params.append("page","1");
    params = params.append("size","300");
    
    return this.httpClient.get(`${environment.apiVersionPath}/notifications`,{ params: params });
  }

  getApiKeys(): Observable<any> {
    return this.httpClient.get(`${environment.apiVersionPath}/apikeys`);
  }

  addApikey(userId, body): Observable<any> {
    return this.httpClient.post(`${environment.apiVersionPath}/apikeys/${userId}`, body);
  }

  revokeApikey(id): Observable<any> {
    return this.httpClient.put(`${environment.apiVersionPath}/apikeys/${id}/revoke`, null);
  }

  delApikey(id): Observable<any> {
    return this.httpClient.delete(`${environment.apiVersionPath}/apikeys/${id}`);
  }

  getScenarios(userId) : Observable<any> {
    return this.httpClient.get(`${environment.apiVersionPath}/users/${userId}/scenarios`).pipe(map((scenarios:any)=>{
      scenarios.results.forEach(s => {
        s.description = decodeURI(s.description);
      });
      return scenarios;
    }));
  }
}
