import React from 'react';
import PropTypes from 'prop-types';

const GeolocationService = function () {
  let watcherID;
  let initTime;

  const init = () => {
    if (navigator.geolocation) {
      stop();
      initTime = new Date();
      watcherID = navigator.geolocation.watchPosition(geoLocationSuccess, geoLocationError, geoLocationOption());
      // console.log(`Start finding location: Watcher ID (${watcherID})`);
    }
  };

  const geoLocationSuccess = (position) => {
    const seconds = (new Date().getTime() - initTime.getTime()) / 1000;

    // console.log(`Current Position (took ${seconds}s): `);
    localStorage.setItem('currentLocation', JSON.stringify({ lat: position.coords.latitude, long: position.coords.longitude }));

    initTime = new Date();
  };

  const geoLocationError = (error) => {
    console.error('Error to get position: ', error);
    // init();
  };

  const geoLocationOption = () => {
    return {
      enableHighAccuracy: true,
    };
  };

  const getCoordinates = () => {
    const currentLocation = localStorage.getItem('currentLocation');
    if (currentLocation) {
      let geo = JSON.parse(currentLocation);
      if (!geo.lat || !geo.long) {
        return { lat: 41.819078, long: -87.623129 };
      } else {
        return geo;
      }
    } else {
      return { lat: 41.819078, long: -87.623129 };
    };
  };

  const stop = () => {
    if (watcherID) {
      navigator.geolocation.clearWatch(watcherID);
    }
  };

  init();

  return {
    Stop: stop,
    GetCoordinates: getCoordinates,
  };
}();

module.exports = GeolocationService;
