import { inject, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { SortDescriptor } from '@progress/kendo-data-query';
import { SosItem } from '../models';

export interface SosSettingItem {
  fontSize: number;
  mainFrozenColumnCount: number;
  mainDisplayInfos: DisplayInfo[];
  transferFrozenColumnCount: number;
  transferDisplayInfos: DisplayInfo[];
  sorts: SortDescriptor[];
}

export interface DisplayInfo {
  propName: string;
  displayName: string;
  width: number;
  isVisible: boolean;
  order: number;
  sortDir: 'asc' | 'desc';
  sortNum: number;
}

export interface PipeAndDefaultSettings {
  pipeSettings: SosSettingItem;
  defaultSettings: SosSettingItem;
}

export interface AllDisplayInfos {
  allMainColumnDisplayInfos: DisplayInfo[];
  allTransferColumnDisplayInfos: DisplayInfo[];
}

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

  getSettings(pipeId: number): Observable<PipeAndDefaultSettings> {
    const url = `${this.baseUrl}/GetSettings?pipeId=${pipeId}`;
    return this.http.get<PipeAndDefaultSettings>(url);
  }

  getAllColumnDisplayInfos(): Observable<AllDisplayInfos> {
    const url = `${this.baseUrl}/GetAllColumnDisplayInfos`;
    return this.http.get<AllDisplayInfos>(url);
  }

  saveSettings(settings: PipeAndDefaultSettings, loadedPipeId: number): Observable<SosSettingItem> {
    const url = `${this.baseUrl}/SaveSettings?savePipeId=${loadedPipeId}`;
    return this.http.post<SosSettingItem>(url, settings);
  }

  saveSelectedPoint(pointId: number) {
    const url = `${this.baseUrl}/SaveSelectedPoint?pointId=${pointId}`;
    return this.http.put(url, null);
  }

  saveSort(sorts: SortDescriptor[], pipeId: number) {
    const url = `${this.baseUrl}/SaveSort?pipeId=${pipeId}`;
    return this.http.put(url, sorts);
  }

  setItemDisplay(item: SosItem, deliveryPointId: number) {
    const url = `${this.baseUrl}/SetItemDisplay?deliveryPointId=${deliveryPointId}`;
    return this.http.put(url, item);
  }
}
