import { Injectable } from '@angular/core';
import { ConfigService } from '@shared/config/config.service';
import { FleioApiService } from '../../fleio-api.service';
import { HttpClient } from '@angular/common/http';
import { IUserModel } from '../model/user.model';
import { FleioId } from '../../base-model/base-fleio-object.model';
import { Observable } from 'rxjs';
import { IClientModel } from '@fleio-api/client-user/model/client.model';

@Injectable({
  providedIn: 'root'
})
export class UsersApiService extends FleioApiService<IUserModel> {
  // noinspection JSUnusedGlobalSymbols
  constructor(protected httpClient: HttpClient, protected config: ConfigService) {
    super();
    this.setEndpoint(config.getPanelApiUrl('users'));
  }

  addToGroup(
    objectId: FleioId,
    groupId: FleioId
  ): Observable<any> {
    return this.objectPostAction(objectId, `add_user_to_group?group_id=${groupId}`, {});
  }

  removeFromGroup(
    objectId: FleioId,
    groupId: FleioId
  ): Observable<any> {
    return this.objectPostAction(objectId, `remove_user_from_group?group_id=${groupId}`, {});
  }

  getUsersInGroup(groupId: FleioId, page: number): Observable<any> {
    return this.getAction('get_users_in_group', {
      group_id: groupId,
      page
    });
  }

  getAvailableUsersForGroup(groupId: FleioId, search: string): Observable<any> {
    return this.list({
      search,
      filtering: `groups__ne:${groupId}`
    });
  }

  impersonate(userId: FleioId): Observable<any> {
    return this.objectPostAction(userId, 'impersonate', {action: 'impersonate'});
  }

  getClients(userId: FleioId): Observable<{ clients: IClientModel[] }> {
    return this.objectGetAction(userId, 'get_clients', {});
  }

  associateClient(userId: FleioId, clientId: FleioId, roles: number[]) {
    return this.objectPostAction(userId, 'associate_client', {id: userId, client_id: clientId, roles});
  }
}
