import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { IListItemAclRights } from '../models/list.item.acl.rights';
import { ISharedItem } from '../models/shared.item';
import { AppConfig } from '../shared/app.config';
import { IListItem } from '../models/list.item';

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

  constructor(
    public httpClient: HttpClient,
    public appConfig: AppConfig) {
  }

  apiEndpoint() {
    return this.appConfig.getConfig('apiEndPoint');
  }

  public getSharedUsersForItem(itemCode: string): Observable<any> {
    return this.httpClient.get<any>(`${this.apiEndpoint()}/api/v1/items/${itemCode}/sharedusers`);
  }

  getSharedItemsWithRightsInfo(userCode: string): Observable<ISharedItem[]> {
    return this.httpClient.get<any>(`${this.apiEndpoint()}/api/v1/users/${userCode}/shared`);
  }

  shareItem(itemCode: string, userCode: string, userRights: string, expireTimespan: string, deep: boolean): Observable<any> {
    const body = {
      rights: userRights,
      expire: expireTimespan,
      deep: deep
    };

    return this.httpClient.post<any>(`${this.apiEndpoint()}/api/v1/items/${itemCode}/share/${userCode}`, body);
  }

  revokeSharedItem(itemCode: string, userCode: string): Observable<any> {
    return this.httpClient.delete<any>(`${this.apiEndpoint()}/api/v1/items/${itemCode}/share/${userCode}`);
  }

  getSharedItemRights(sharedByMe: boolean): Observable<IListItemAclRights[]> {
    let params = new HttpParams();
    params = params.append('byMe', sharedByMe);

    return this.httpClient.get<any>(`${this.apiEndpoint()}/api/v1/user/rights`, {params: params});
  }

  getSharedItemsByParent(parentCode: string): Observable<ISharedItem[]> {
    return this.httpClient.get<any>(`${this.apiEndpoint()}/api/v1/items/${parentCode}/sharedchildren`);
  }

  getSharedWithCurrentUser(profile: string): Observable<IListItem[]> {
    let params = new HttpParams();
    if (profile != null) {
      params = params.append('sharedBy', profile);
    }

    return this.httpClient.get<any>(`${this.apiEndpoint()}/api/v1/items/shared/`, {params: params});
  }

  // this method does not belong here, belongs in some sort of item service
  public copyItem(itemCode: string, newParentCode: string, newUserCode: string): Observable<any> {
    const body = {
      itemCode: itemCode,
      newParentCode: newParentCode,
      newUserCode: newUserCode
    };
    return this.httpClient.post<any>(`${this.apiEndpoint()}/api/v1/items/copy`, body);
  }
}
