import fetch from 'node-fetch';

import MatchingWorkflow from '../../Workflows/MatchingWorkflow';
import { formatUsersLocations } from '../../Mapper/Geolocation';

const BASE_URL = 'http://geolocations-dev.madbean.ovh';

// resolvers setters
const updateGeolocation = async (location) => {
  const options = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
    },
    body: JSON.stringify([{
      latitude: location.lat,
      longitude: location.lon,
      key: location.key,
    }]),
  };

  // update location
  try {
    const updated = await fetch(`${BASE_URL}/${location.collectionID}`, options).then(data => data.json());
    if (location.fetchCloseUsers && updated.data.success) {
      // find close users
      return MatchingWorkflow().execMatchingWorkflow(location, getCloseUsersLocations);
    }
  } catch (err) {
    console.error(err);
  }

  return [];
};

// resolvers
const getJSONFromRelativeURL = relativeURL => fetch(`${BASE_URL}${relativeURL}`)
  .then(res => res.json());

const getLocationByURL = relativeURL => getJSONFromRelativeURL(relativeURL)
  .then(json => json);

const getLocation = ({ id, key }) => getLocationByURL(`/${id}/${key}`);

const getDistanceLocation = ({ id, key, foreignKey }) => getLocationByURL(`/${id}/${key}/${foreignKey}`);

const getCloseUsersLocations = ({
  id, key, distance, unit,
}) =>
  getLocationByURL(`/${id}/${key}/${distance}/${unit}`)
    .then(json => formatUsersLocations(json.data));

export default {
  getCloseUsersLocations,
  getDistanceLocation,
  getLocation,
  updateGeolocation,
};
