import { HttpClient, HttpParams } from "@angular/common/http";
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { IItem } from '../models/item';
import { IItemTask } from '../models/itemTask';
import { IUser } from '../models/user';
import { AppConfig } from "../shared/app.config";
import { ItemTypeService } from './itemtype.service';

@Injectable({
  providedIn: 'root',
})
export class AdminService {
  constructor(public httpClient: HttpClient, public appConfig: AppConfig,private itemTypeService:ItemTypeService) {
  }

  ApiEndpoint() {
    return this.appConfig.getConfig("apiEndPoint");
  }

  getItem(code: string): Observable<IItem> {
    return this.httpClient.get<IItem>(`${this.ApiEndpoint()}/api/v1/admin/${code}`);
  }

  getItemList(itemType?: string, dataFilter?: any, level?: number, atItemLocationItemCode?: string, indexed?: boolean, validToday?: boolean): Observable<IItem[]> {
    let params = new HttpParams();
    if(itemType)  params = params.append("it", itemType);
    if(dataFilter) params = params.append("df", JSON.stringify(dataFilter));
    if(atItemLocationItemCode) params = params.append("ail",atItemLocationItemCode);
    if(indexed) params = params.append("ind",indexed?"true":"false");
    if (level) params = params.append("lvl", level.toFixed());
    if (validToday) params = params.append("vt", validToday ? "true" : "false");
    return this.httpClient.get<IItem[]>(`${this.ApiEndpoint()}/api/v1/admin/`, { params: params });
  }

  postItem(item:IItem): Observable<IItem> {
    return this.httpClient.post<IItem>(`${this.ApiEndpoint()}/api/v1/admin`,item);
  }

  putItem(item:IItem): Observable<IItem> {
    return this.httpClient.put<IItem>(`${this.ApiEndpoint()}/api/v1/admin/${item.code}`,item);
  }

  deleteItem(code: string): Observable<any> {
    return this.httpClient.delete<any>(`${this.ApiEndpoint()}/api/v1/admin/${code}`);
  }

  getAllUsers(): Observable<IUser[]> {
    return this.httpClient.get<IUser[]>(`${this.ApiEndpoint()}/api/v1/admin/users`);
  }

  postItemTask(item: IItem, task: IItemTask): Observable<IItemTask> {
    return this.httpClient.post<IItemTask>(`${this.ApiEndpoint()}/api/v1/admin/${item.code}/tasks`, task);
  }

  getFileStorageOverview(): Observable<any> {
    return this.httpClient.get<any>(`${this.ApiEndpoint()}/api/v1/admin/filestorage/folderinfo/overview`);
  }

  getFileStorageInfo(user: string): Observable<any> {
    return this.httpClient.get<any>(`${this.ApiEndpoint()}/api/v1/admin/filestorage/folderinfo/${user}`);
  }

  getFileStorageLog(): Observable<any> {
    return this.httpClient.get<any>(`${this.ApiEndpoint()}/api/v1/admin/filestorage/folderinfo/log`);
  }

  validateEmail(user: IUser) {
    return this.httpClient.post(`${this.ApiEndpoint()}/api/v1/admin/user/${user.code}/validateemail`, user);
  }
}
