import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { ItemDetail, SearchItemDetailModel } from '../models/itemDetail.model';
import { Observable } from 'rxjs';

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

  constructor(private http: HttpClient) { }
  url: string = "http://b872-2405-9800-bc03-3665-282a-83c6-a83e-fc1b.ngrok.io";
  listItemDetail: ItemDetail[] = []

  addItemDetail(model: ItemDetail) {
    console.log(this.listItemDetail);
    this.listItemDetail.push(model);
    this.listItemDetail.reverse
  }

  getListItemDetail(): Observable<ItemDetail[]> {
    return this.http.get<ItemDetail[]>(this.url + "/lend/lists");
  }

  searchListItemDetail(searchModel: SearchItemDetailModel) {
    this.http.get(this.url + '&startDate=' + searchModel.sDate.split("-")[2] + '-' + searchModel.sDate.split("-")[1] + '-' + searchModel.sDate.split("-")[0] + '&endDate=' + searchModel.eDate.split("-")[2] + '-' + searchModel.eDate.split("-")[1] + '-' + searchModel.eDate.split("-")[0] + '&startTime=' + searchModel.sTime + ':00' + '&endTime=' + searchModel.eTime + ':00').subscribe((response: any) => {
      console.log(response);
      this.listItemDetail = response;
    }, error => {
      console.log(error)
      alert("ไม่สามารถค้นหาอุปกรณ์ที่ว่างได้ เนื่องจาก :\n" + error.message)
    })
  }

  deleteItemDetail(model: ItemDetail) {
    this.http.delete(this.url + "/" + model.id).subscribe(response => {
      console.log(response);
      this.getListItemDetail()
      alert("ลบข้อมูลอุปกรณ์สำเร็จ")
    })
  }

  updateItemDetail(model: ItemDetail) {
    this.http.put(this.url + "/lend/" +model.id, model).subscribe(response => {
      console.log(response);
      alert("อัพเดทข้อมูลอุปกรณ์สำเร็จ")
    })
  }

}