import { inject, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { IdName } from '../_shared/utils/util';
import { Observable } from 'rxjs';
import { FilterValue } from '../filter-controls/control-base.component';

export interface ReportFilter {
  id: number,
  name: string,
  isSelected: boolean
}

export enum EditorType {
  AddNew,
  Rename,
  Copy
}

@Injectable({
  providedIn: 'root'
})
export class ReportFilterService {
  private baseUrl = `${window.location.origin}/api/ReportFilter`;
  http = inject(HttpClient);


  getFilters(reportId: number): Observable<ReportFilter[]> {
    const url = `${this.baseUrl}/getFilters?reportId=${reportId}`;
    return this.http.get<ReportFilter[]>(url);
  }

  addFilter(reportId: number, name: string): Observable<number> {
    const url = `${this.baseUrl}/addFilter?reportId=${reportId}&name=${name}`;
    return this.http.post<number>(url, null);
  }

  renameFilter(id: number, name: string): Observable<string> {
    const url = `${this.baseUrl}/renameFilter?id=${id}&name=${name}`;
    return this.http.post(url, null, { observe: 'response', responseType: 'text' }).pipe(
      map(result => {
        return result.body;
      })
    );
  }

  copyFilter(id: number, name: string): Observable<number> {
    const url = `${this.baseUrl}/copyFilter?id=${id}&name=${name}`;
    return this.http.post(url, null, { observe: 'response', responseType: 'text' }).pipe(
      map(result => {
        return parseInt(result.body);
      })
    );
  }

  deleteFilter(id: number) {
    const url = `${this.baseUrl}/deleteFilter/${id}`;
    return this.http.delete(url);
  }

  getDataSources(reportId: number): Observable<IdName[]> {
    const url = `${this.baseUrl}/getDataSources?reportId=${reportId}`;
    return this.http.get<IdName[]>(url);
  }

  saveFilter(reportId: number, filterId: number, filterValues: FilterValue[]) {
    const filterIdStr = filterId ?? '';
    const url = `${this.baseUrl}/saveFilter?reportId=${reportId}&filterId=${filterIdStr}`;
    return this.http.put(url, filterValues);
  }

  getFilterParams(filterId: number): Observable<FilterValue[]> {
    const url = `${this.baseUrl}/getFilterParams?filterId=${filterId}`;
    return this.http.get<FilterValue[]>(url);
  }

  setFilterSelected(reportId: number, filterId: number) {
    const filterIdStr = filterId ?? '';
    const url = `${this.baseUrl}/SetFilterSelected?reportId=${reportId}&filterId=${filterIdStr}`;
    return this.http.put(url, null);
  }

  copyFilterToAllUsers(filterId: number) {
    const url = `${this.baseUrl}/CopyFilterToAllUsers?filterId=${filterId}`;
    return this.http.put(url, null);
  }
}
