import React, { createContext, useContext, useState, ReactNode, useEffect } from 'react';
import { useIdle } from 'react-use';
import { useMyIonMetric } from './MyIonMetric';
import { useAppUseTime } from './MyIonMetric/AppUseTime';

const AppOnRecorderContext = createContext<MyContextProps | undefined>(undefined);

export const AppOnRecorderProvider: React.FC = () => {
  const [my_context, setMyContext] = useState<string>('initial value');
  const { myIonMetricIncAppUseTime } = useAppUseTime();

  const isIdle = useIdle(3e3);
  let getCurrentTimeInSec = () => Math.floor(Date.now() / 1000);
  let [last_on_s, setLastOn_s] = useState(getCurrentTimeInSec());

  useEffect(() => {
    (async () => {
      if (isIdle) {
        // active -> inactive
        let current_s = getCurrentTimeInSec();
        myIonMetricIncAppUseTime(current_s - last_on_s);
      } else {
        // inactive->active
        setLastOn_s(getCurrentTimeInSec());
      }
    })();
  }, [isIdle]);

  return <AppOnRecorderContext.Provider value={{ my_context, setMyContext }}>{/*  */}</AppOnRecorderContext.Provider>;
};

export const useMyContext = (): MyContextProps => {
  const context = useContext(AppOnRecorderContext);
  if (!context) {
    throw new Error('useMyContext must be used within a MyProvider');
  }
  return context;
};

interface MyContextProps {
  my_context: string;
  setMyContext: React.Dispatch<React.SetStateAction<string>>;
}
