import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { lastValueFrom, Observable } from 'rxjs'; import { CityAndStateResult, CountyResult, GeoResult, IpInfo } from '../../../../bizmatch-server/src/models/main.model'; import { Place } from '../../../../bizmatch-server/src/models/server.model'; import { environment } from '../../environments/environment'; @Injectable({ providedIn: 'root', }) export class GeoService { private apiBaseUrl = environment.apiBaseUrl; private baseUrl: string = 'https://nominatim.openstreetmap.org/search'; private fetchingData: Observable | null = null; private readonly storageKey = 'ipInfo'; constructor(private http: HttpClient) {} findCitiesStartingWith(prefix: string, state?: string): Observable { const stateString = state ? `/${state}` : ''; return this.http.get(`${this.apiBaseUrl}/bizmatch/geo/${prefix}${stateString}`); } findCitiesAndStatesStartingWith(prefix: string): Observable { return this.http.get(`${this.apiBaseUrl}/bizmatch/geo/citiesandstates/${prefix}`); } findCountiesStartingWith(prefix: string, states?: string[]): Observable { return this.http.post(`${this.apiBaseUrl}/bizmatch/geo/counties`, { prefix, states }); } findLocationStartingWith(prefix: string): Observable { let headers = new HttpHeaders().set('X-Hide-Loading', 'true').set('Accept-Language', 'en-US'); return this.http.get(`${this.baseUrl}?q=${prefix},US&format=json&addressdetails=1&limit=5`, { headers }) as Observable; } getCityBoundary(cityName: string, state: string): Observable { const query = `${cityName}, ${state}, USA`; let headers = new HttpHeaders().set('X-Hide-Loading', 'true').set('Accept-Language', 'en-US'); return this.http.get(`${this.baseUrl}?q=${encodeURIComponent(query)}&format=json&polygon_geojson=1&limit=1`, { headers }); } private fetchIpAndGeoLocation(): Observable { return this.http.get(`${this.apiBaseUrl}/bizmatch/geo/ipinfo/georesult/wysiwyg`); } async getIpInfo(): Promise { // Versuche zuerst, die Daten aus dem sessionStorage zu holen const storedData = sessionStorage.getItem(this.storageKey); if (storedData) { return JSON.parse(storedData); } try { // Wenn keine Daten im Storage, hole sie vom Server const data = await lastValueFrom(this.http.get(`${this.apiBaseUrl}/bizmatch/geo/ipinfo/georesult/wysiwyg`)); // Speichere die Daten im sessionStorage sessionStorage.setItem(this.storageKey, JSON.stringify(data)); return data; } catch (error) { console.error('Error fetching IP info:', error); return null; } } }