import {
  GeolocationResponse
} from "@react-native-community/geolocation";
import { CHUCKS_PAD } from "appConstants/e2e";
import {
  LOCATION_PERMISSIONS,
  permissionResultFromMultiple
} from "components/SharedComponents/PermissionGateContainer";
import { Platform } from "react-native";
import {
  checkMultiple,
  RESULTS
} from "react-native-permissions";

let counter = 0;

function getCurrentPosition(
  success: (position: GeolocationResponse) => void,
  error?: (error: any) => void,
  options?: any
) {
  console.log("[DEBUG geolocationWrapper.e2e-mock] getCurrentPosition");
  setTimeout(() => {
    console.log("[DEBUG geolocationWrapper.e2e-mock] getCurrentPosition success");
    success({
      coords: CHUCKS_PAD,
      timestamp: Date.now()
    });
  }, 500);
}

function watchPosition(
  success: ( position: GeolocationResponse ) => void
) {
  console.log( "[DEBUG geolocationWrapper.e2e-mock] watchPosition" );
  const watchID = Date.now();
  /*
    We have to limit this here to not run forever otherwise the e2e
    test never idles and times out.
  */
  if ( counter < 5 ) {
    setTimeout( ( ) => {
      console.log( "[DEBUG geolocationWrapper.e2e-mock] watchPosition success" );
      counter += 1;
      success( {
        coords: CHUCKS_PAD,
        timestamp: Date.now()
      } );
    }, 1000 );
  }
  return watchID;
}

function clearWatch( watchID: number ) {
  console.log( "[DEBUG geolocationWrapper.e2e-mock] clearWatch, watchID: ", watchID );
}

const highAccuracyOptions = {
  enableHighAccuracy: true,
  timeout: 10000,
  ...( Platform.OS === "ios" && { maximumAge: 0 } )
};

const lowAccuracyOptions = {
  enableHighAccuracy: false,
  timeout: 2000,
  ...( Platform.OS === "ios" && { maximumAge: 0 } )
};

const getCurrentPositionWithOptions = (
  options
): Promise<GeolocationResponse> => new Promise(
  ( resolve, reject ) => {
    console.log("[DEBUG geolocationWrapper.e2e-mock] getCurrentPositionWithOptions");
    getCurrentPosition( resolve, reject, options );
  }
);

const checkLocationPermissions = async ( ) => {
  const permissionResult = permissionResultFromMultiple(
    await checkMultiple( LOCATION_PERMISSIONS )
  );
  console.log("[DEBUG geolocationWrapper.e2e-mock] checkLocationPermissions");

  if ( Platform.OS !== "android" && permissionResult !== RESULTS.GRANTED ) {
    return null;
  }
  return permissionResult;
};

export {
  clearWatch,
  watchPosition,
  highAccuracyOptions,
  lowAccuracyOptions,
  getCurrentPositionWithOptions,
  checkLocationPermissions
};
