import React, { useEffect, useState, useRef } from 'react';
import PropTypes from 'prop-types';
import { withTracker } from 'meteor/react-meteor-data';
import WakeLock from './component';
import Service from './service';
import getFromUserSettings from '/imports/ui/services/users-settings';
import useUserChangedLocalSettings from '../../services/settings/hooks/useUserChangedLocalSettings';
import useSettings from '../../services/settings/hooks/useSettings';
import { SETTINGS } from '../../services/settings/enums';

const propTypes = {
  areAudioModalsOpen: PropTypes.bool,
  autoJoin: PropTypes.bool.isRequired,
};

const defaultProps = {
  areAudioModalsOpen: false,
};

function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
}

const WakeLockContainer = (props) => {
  if (!Service.isMobile()) return null;

  const { areAudioModalsOpen, autoJoin } = props;
  const wereAudioModalsOpen = usePrevious(areAudioModalsOpen);
  const [endedAudioSetup, setEndedAudioSetup] = useState(false || !autoJoin);
  const setLocalSettings = useUserChangedLocalSettings();
  const { wakeLock: wakeLockSettings } = useSettings(SETTINGS.APPLICATION);

  useEffect(() => {
    if (wereAudioModalsOpen && !areAudioModalsOpen && !endedAudioSetup) {
      setEndedAudioSetup(true);
    }
  }, [areAudioModalsOpen]);

  return endedAudioSetup ? (
    <WakeLock
      setLocalSettings={setLocalSettings}
      wakeLockSettings={wakeLockSettings}
      {...props}
    />
  ) : null;
};

WakeLockContainer.propTypes = propTypes;
WakeLockContainer.defaultProps = defaultProps;

export default withTracker(() => {
  const APP_CONFIG = window.meetingClientSettings.public.app;

  return {
    request: Service.request,
    release: Service.release,
    areAudioModalsOpen: Session.get('audioModalIsOpen') || Session.get('inEchoTest'),
    autoJoin: getFromUserSettings('bbb_auto_join_audio', APP_CONFIG.autoJoin),
  };
})(WakeLockContainer);
