import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { IItem } from '../models/item';
import { HttpClient, HttpParams } from "@angular/common/http";
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}`);
  }
}
