import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';
import { UiService } from './ui.service';


/**************************  
 Created by Ajith A Pradeep
 Created on 04/04/2022
 **************************/

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

  loading: boolean = false;

  constructor(
    private http: HttpClient,
    private _uiService: UiService
  ) { }



  async getMasterData(apiUrl, filter?: string): Promise<any> {
    if (!filter)
      filter = ''
    return await this.http.get<any>(`${environment.apiUrl}/${apiUrl}${filter}`).toPromise();
  }

  async getMasterDatabyId(apiUrl, id): Promise<any> {
    return await this.http.get<any>(`${environment.apiUrl}/${apiUrl}/${id}`).toPromise();
  }

  async saveMasterData(apiUrl, body): Promise<any> {
    return await this.http.post<any>(`${environment.apiUrl}/${apiUrl}`, body).toPromise();
  }

  async saveAllMasterData(apiUrl, body): Promise<any[]> {
    return await this.http.post<any[]>(`${environment.apiUrl}/${apiUrl}`, body).toPromise();
  }

  async postMasterData(apiUrl, body, id): Promise<any> {
    return await this.http.post<any>(`${environment.apiUrl}/${apiUrl}/${id}`, body).toPromise();
  }

  async updateMasterData(apiUrl, body, id): Promise<any> {
    return await this.http.put<any>(`${environment.apiUrl}/${apiUrl}/${id}`, body).toPromise();
  }

  async deleteMasterDataById(apiUrl, body, id): Promise<any> {
    return await this.http.delete<any>(`${environment.apiUrl}/${apiUrl}/${id}`, body).toPromise();
  }
  async deleteMasterData(apiUrl, id): Promise<any[]> {
    return await this.http.delete<any>(`${environment.apiUrl}/${apiUrl}/${id}`).toPromise();
  }

  async saveImage(apiUrl, body): Promise<any> {
    return await this.http.post<any>(`${environment.apiUrl}/${apiUrl}`, body).toPromise();
  }

  async getImg(apiUrlEnd: string, imagePath: string) {
    return await this.http.get(`${environment.apiUrl}/${apiUrlEnd}/${imagePath}`, { responseType: 'blob' }).toPromise();
  }

  async getJsonData(name: string): Promise<any> {
    if (!name || name.trim() == "") return {};
    return await this.http.get(`assets/i18n/json/${name}.json`).toPromise();
  }


  async getLovDataFormat(endUrl, filterCondition?) {
    let data = []
    this.loading = true;
    let filter = ''
    if (filterCondition) {
      filter = filterCondition
    }
    await this.getMasterData(endUrl, filter).then((res: any[]) => {
      data = res;
      this.loading = false;
    },
      err => {
        this.loading = false;
      //  console.log("----err----", err);
        this._uiService.toastMessage(err.error.message, 5000, true);
      });
    return data;
  }

}
