import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { ApiRequestService } from './api-request.service';
import { Observable } from 'rxjs';
import { ReportBuilder } from '../../models/builder/ReportBuilder';
import { ReportBuilderQuery } from '../../models/builder/ReportBuilderQuery';
import { TableList } from '../../models/fnd/TableList';
import { RptBuilder } from 'src/app/models/builder/rptBuilder';
import baseUrl from '../api/helper';
import { saveAs } from 'file-saver';

@Injectable({
  providedIn: 'root'
})
export class ReportBuilderService {
  private reportBaseURL ='api/report-builder-by-id';
  private reportBaseURLSubmit ='api/report-builder';
  private masterQueryUrl ='api/add-master-query';
  private storage: Storage = sessionStorage;
  private moduleIdKey: string = "moduleId";
  private baseURLMasterQuery="api/master-query";
  private baseURL="api/edit-report";
  private reportbuild2url="api/add-report";
  private  servicereportsave="api/report-builder_service";
  private updatereportservice="api/updatereport";

  private databaselisturl='Table_list'
  private colurl='fndMenu/loadcolumn';
  private saveurl='FndQuery/query';
  constructor(private apiRequest: ApiRequestService, private _http:HttpClient) { }
  getById(id: number): Observable<ReportBuilder> {
    const _http = this.baseURL + "/" + id;
    return this.apiRequest.get(_http);
  }

  buildReport(id: number) {
    let params: HttpParams = new HttpParams();
    params = params.append("id", id.toString());
    return this.apiRequest.get("api/build_report", params);
  }

  getModuleId(): number {
    let modId = +this.storage.getItem(this.moduleIdKey);
    return modId;
  }

  getAll(moduleId: number, page?: number, size?: number): Observable<any> {
    // create Request URL params
    let me = this;
    let params: HttpParams = new HttpParams();
    params = params.append("page", typeof page === "number" ? page.toString() : "0");
    params = params.append("size", typeof size === "number" ? size.toString() : "1000");
    params = params.append("moduleId", moduleId.toString());
    // get all
    return this.apiRequest.get(this.reportBaseURL, params);
  }

  //save report
  create(fbHeader: ReportBuilder, moduleId: number): Observable<ReportBuilder> {
    //`${this.baseURL}`
    let params: HttpParams = new HttpParams();
    params = params.append("moduleId", moduleId.toString());
   // params = params.append("formType", formType);
    return this.apiRequest.post(this.reportBaseURLSubmit, fbHeader, params);
  }

  //save report service
  createservicereport(fbHeader: ReportBuilder, moduleId: number): Observable<ReportBuilder> {
    //`${this.baseURL}`
    let params: HttpParams = new HttpParams();
    params = params.append("moduleId", moduleId.toString());
   // params = params.append("formType", formType);
    return this.apiRequest.post(this.servicereportsave, fbHeader, params);
  }

  //save report
  createQuery(reportId: number): Observable<any> {
    //`${this.baseURL}`
    let params: HttpParams = new HttpParams();
    params = params.append("reportId", reportId.toString());
   // params = params.append("formType", formType);
    return this.apiRequest.post(this.masterQueryUrl,params);
  }

  // update(reportId: number, functionRegister: ReportBuilder): Observable<ReportBuilder> {
  //   let params: HttpParams = new HttpParams();
  //   params = params.append("reportId", reportId.toString());
  //   return this.apiRequest.put(this.masterQueryUrl/reportId, functionRegister);
  // }

  update(id: number, functionRegister: ReportBuilder): Observable<ReportBuilder> {
    const _http = this.masterQueryUrl + "/" + id;
    return this.apiRequest.put(_http, functionRegister);
  }

  updateservicereport(id: number, functionRegister: ReportBuilder): Observable<ReportBuilder> {
    const _http = this.updatereportservice + "/" + id;
    return this.apiRequest.put(_http, functionRegister);
  }

  getMasterQuery(id: number): Observable<ReportBuilderQuery> {
    const _http = this.baseURLMasterQuery + "/" + id;
    return this.apiRequest.get(_http);
  }

  getMasterData(query:string): Observable<any> {
    //Create Request URL params
    let me = this;
    let params: HttpParams = new HttpParams();
     params = params.append('sql_query', query);
    return this.apiRequest.get('api/master-query-data',params);
}


 report2(servicename):Observable<any>
{
  console.log("in service",servicename);

  // let params: HttpParams = new HttpParams();
  // params = params.append('service_name', servicename);

  // console.log(this.reportbuild2url,params);

  return this.apiRequest.post(this.reportbuild2url,servicename);
}


//savequery
saveq(data:any):Observable<any>{
  return this.apiRequest.post(this.saveurl,data);
}
//getall
getall(){
  return this.apiRequest.get(this.saveurl);
}

///////
getreportdata(apiname):Observable<any>
{
 var url="api"+"/"+apiname;
 console.log(url)

 return this.apiRequest.get(url);

}
getdatabse(): Observable<any>{
  return this.apiRequest.get(`SqlworkbenchSqlcont/sql`);
  //return this.apiRequest.get(this.databaselisturl);
}
getTableListn(val:any): Observable<TableList[]> {
  return this.apiRequest.get(`Table_list/${val}`);
}
getcolListn(val:any,val1:any): Observable<TableList[]> {
  return this.apiRequest.get(`Table_list/${val}/${val1}`);
}

//column list for multiple tables
getColumnList(tableSchema: any, tables: any): Observable<any> {
  // return this._http.get( `http://localhost:9191/AllTable_list/${tableSchema}`,tables);
  const params = new HttpParams().set('str', tables.join(','));
  return this._http.get(`${baseUrl}/AllTable_list/${tableSchema}`,  { params: params });
}

//working column list for multiple tables with alias
getAllColumnsFromAllTables(tableNames: any): Observable<any> {
  const url = `${baseUrl}/Alias_Table_list/${tableNames}`;
  return this._http.get(url);
}

getcollist(table:any){
  const _http = this.colurl+ "/" + table;
  return this.apiRequest.get(_http);
  //return this.apiRequest.get(`this.colurl/${table}`);
}
createdb(data:any){
  return this.apiRequest.post(`SqlworkbenchSqlcont/sql`,data);
}

updateSqlModel(id: number, sqlModel: any): Observable<any> {
  return this.apiRequest.put(`SqlworkbenchSqlcont/sql/${id}`, sqlModel);
}

getSqlModelById(id: number): Observable<any> {
  return this.apiRequest.get(`SqlworkbenchSqlcont/sql/${id}`);
}

deleteSqlModel(id: number): Observable<any> {
  return this.apiRequest.delete(`SqlworkbenchSqlcont/sql/${id}`);
}

getallentity(){
  return this.apiRequest.get(this.reportBaseURLSubmit);
}


////////// rpt builders //////////////

saveData(data: RptBuilder): Observable<RptBuilder> {
  return this.apiRequest.post(`Rpt_builder/Rpt_builder`, data);
}

getDetails(): Observable<any> {
  return this.apiRequest.get(`Rpt_builder/Rpt_builder`);
}

getDetailsById(id: number): Observable<any> {
  return this.apiRequest.get(`Rpt_builder/Rpt_builder/${id}`);
}

deleteById(id: number): Observable<any> {
  return this.apiRequest.delete(`Rpt_builder/Rpt_builder/${id}`);
}

updateData(data: any, id: number): Observable<any> {
  return this.apiRequest.put(`Rpt_builder/Rpt_builder/${id}`, data);
}


////////// rpt builders 2//////////////

saverbData(data: any): Observable<any> {
  return this.apiRequest.post(`Rpt_builder2/Rpt_builder2`, data);
}

getrbDetails(): Observable<any> {
  return this.apiRequest.get(`Rpt_builder2/Rpt_builder2`);
}

getrbDetailsById(id: number): Observable<any> {
  return this.apiRequest.get(`Rpt_builder2/Rpt_builder2/${id}`);
}

deletrbById(id: number): Observable<any> {
  return this.apiRequest.delete(`Rpt_builder2/Rpt_builder2/${id}`);
}

updaterbData(data: any, id: number): Observable<any> {
  return this.apiRequest.put(`Rpt_builder2/Rpt_builder2/${id}`, data);
}

updaterbLineData(data: any, id: number): Observable<any> {
  return this.apiRequest.put(`Rpt_builder2_lines/update/${id}`, data);
}

getrbLineDetailsById(id: number): Observable<any> {
  return this.apiRequest.get(`Rpt_builder2_lines/Rpt_builder2_lines/${id}`);
}

/// rpt builders 2 html 
getStdParamById(id: number): Observable<any> {
  return this.apiRequest.get(`Rpt_builder2/html/build_report2/${id}`);
}
//get key from URL
getcolumnDetailsByurl(url: string): Observable<any> {
  const apiUrl = `Rpt_builder2_lines/geturlkeybyurl?url=${url}`;
  return this.apiRequest.get(apiUrl);
}

getAllDetailsByurl(url: string): Observable<any> {
  const apiUrl = `Rpt_builder2_lines/fetch_data_url?url=${url}`;
  return this.apiRequest.get(apiUrl);
}





///////////////////////////////////////////// DOWNLOADS
// downloadFile(format:any,data: any): Observable<any> {
//   return this.apiRequest.post(`rbbuilder/fileconverter/downloadFile/${format}`, data);
// }

downloadFile(format: string, dataList: any[],name?:String): void {
  const url = `${baseUrl}/rbbuilder/fileconverter/downloadFile/${format}`;
  this.apiRequest.downloadFile(url, dataList).subscribe(
    (response: Blob) => {
      saveAs(response, `${name}.${format}`);
    },
    (error) => {
      console.error('Error downloading file:', error);
    }
  );
}



}
