import { Inject, Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { WINDOW } from './window.token';
const gpsOptions = {
    enableHighAccuracy: false,
    timeout: 10000,
    maximumAge: Infinity,
};

@Injectable({ providedIn: 'root' })
export class GeoService {
    navigator$?: Navigator;
    hasPosition = new BehaviorSubject<boolean>(false);

    constructor(@Inject(WINDOW) window: Window) {
        this.navigator$ = window.navigator;
    }

    getPosition(): Promise<GeolocationCoordinates> {
        return new Promise((resolve, reject) => {
            this.navigator$.geolocation.getCurrentPosition(
                (position) => {
                    this.hasPosition.next(true);
                    resolve(position.coords);
                },
                (error: any) => {
                    reject(error);
                    this.hasPosition.next(false);
                },
                gpsOptions,
            );
        });
    }
}
