// import { Geolocation } from '@capacitor/geolocation';
import { LatLng } from 'src/models';
import { notifyError } from '.';

const DEFAULT_TIMEOUT = 5000;
const DEFAULT_MAX_AGE = 30000;
let watchId: string | null = null;

export async function getCurrentPosition(options?: PositionOptions) {
  const _options = { enableHighAccuracy: true, timeout: DEFAULT_TIMEOUT, maximumAge: DEFAULT_MAX_AGE, ...(options || {}) };
  let memoWatch = false;
  return new Promise<LatLng | null>(async (resolve, reject) => {
    if (navigator.geolocation) {
      if (watchId) {
        memoWatch = true;
        // await clearWatch();
      }
      navigator.geolocation.getCurrentPosition(
        (pos) => resolve({ lat: pos.coords.latitude, lng: pos.coords.longitude } as LatLng),
        (error) => {
          if (error.code === error.PERMISSION_DENIED) {
            notifyError(null, 'Permisos de geolocalización denegados');
          }
          console.log(error.message);
          resolve(null);
        },
        _options
      );
    } else {
      reject(new Error('La geolocalización no es soportada en este navegador.'));
    }
  }).finally(() => {
    if (memoWatch) {
      watchPosition();
    }
  });
}

export async function checkGeolocationPermission() {
  try {
    // const result = await Geolocation.checkPermissions();
    // return result.location;
    throw new Error('Not implemented');
  } catch (err) {
    console.log('Error al verificar permisos de geolocalización usando api de Capacitor', err);
    try {
      const result = await navigator.permissions.query({ name: 'geolocation' });
      return result.state;
    } catch (err) {
      console.log('Error al verificar permisos de geolocalización usando api de navegador', err);
      return null;
    }
  }
}

export async function requestGeolocationPermission() {
  try {
    // await Geolocation.requestPermissions();
    throw new Error('Not implemented');
  } catch (err) {
    await getCurrentPosition(); // esta es la forma nativa de mostrar el dialogo de permiso de geolocalización
  }
}

export async function watchPosition() {
  console.error('not implemented');
  //   if (watchId) {
  //     await clearWatch();
  //   }
  //   watchId = await Geolocation.watchPosition(
  //     {
  //       enableHighAccuracy: true,
  //       timeout: DEFAULT_TIMEOUT,
  //       maximumAge: DEFAULT_MAX_AGE,
  //     },
  //     (position) => {
  //         console.log({position})
  //     }
  //   );
}

/**
  Calcula la distancia lineal entre dos puntos, en kilómetros.  
 */
export function calcLinealDistance(position1: LatLng, position2: LatLng) {
  let { lat: lat1, lng: lon1 } = position1;
  let { lat: lat2, lng: lon2 } = position2;
  let R = 6371; // km
  let dLat = ((lat2 - lat1) * Math.PI) / 180;
  let dLon = ((lon2 - lon1) * Math.PI) / 180;
  lat1 = (lat1 * Math.PI) / 180;
  lat2 = (lat2 * Math.PI) / 180;

  let a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
  let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  let d = R * c;
  return d;
}
