import { useCallback, useEffect, useState } from "react";
import * as uuid from "uuid";

const INSTALL_ID = "installID";
const ONBOARDING_SHOWN = "onboardingShown";
export const IS_FRESH_INSTALL = "isFreshInstall";

const data = new Map();

export const store = {
  getString: ( key ) => data.get( key ),
  set: ( key, value ) => { data.set( key, value ); },
  getBoolean: ( key ) => data.get( key ),
  delete: ( key ) => { data.delete( key ); },
  contains: ( key ) => data.has( key )
};

export function getInstallID( ) {
  const id = store.getString( INSTALL_ID );
  if ( id ) return id;
  const newID = uuid.v4( ).toString( );
  store.set( INSTALL_ID, newID );
  // Skip setting IS_FRESH_INSTALL in e2e to avoid triggering
  // RNRestart.restart() which kills the Detox instrumentation process
  return newID;
}

// Subscribers that get notified when onboardingShown changes, so all
// components using this hook re-render (mimics useMMKVBoolean behavior)
const onboardingListeners = new Set();

export function useOnboardingShown() {
  const [value, setValue] = useState( () => data.get( ONBOARDING_SHOWN ) ?? false );

  useEffect( () => {
    const listener = () => setValue( data.get( ONBOARDING_SHOWN ) ?? false );
    onboardingListeners.add( listener );
    return () => onboardingListeners.delete( listener );
  }, [] );

  const setOnboardingShown = useCallback( newValue => {
    data.set( ONBOARDING_SHOWN, newValue );
    onboardingListeners.forEach( l => l() );
  }, [] );

  return [value, setOnboardingShown];
}
