import React, { createContext, useContext, ReactNode } from 'react';
import { useMyIonMetric } from '.';
import { APP_USE_TIME } from '../../constants';

const AppUseTimeContext = createContext<AppUseTimeContextProps | undefined>(undefined);

export const AppUseTimeProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const { myIonStoreRead, myIonStoreWrite } = useMyIonMetric();

  function Helloworld() {
    console.log('helloworld');
  }

  async function myIonMetricGetAppUseTime() {
    let result = JSON.parse(await myIonStoreRead(APP_USE_TIME, { time_spent_s: 0 }));
    return result;
  }

  async function myIonMetricResetAppUseTime() {
    await myIonStoreWrite(APP_USE_TIME, JSON.stringify({ time_spent_s: 0 }));
  }

  async function myIonMetricIncAppUseTime(time_spent_s: number) {
    let result = await myIonMetricGetAppUseTime();
    await myIonStoreWrite(APP_USE_TIME, JSON.stringify({ time_spent_s: result.time_spent_s + time_spent_s }));
  }

  async function myIonMetricSetAppUseTime(time_spent_s: number) {
    await myIonStoreWrite(APP_USE_TIME, JSON.stringify({ time_spent_s: time_spent_s }));
  }

  async function myIonMetricGetAppUseTimeIgnore() {
    let result = JSON.parse(await myIonStoreRead(APP_USE_TIME + '_ignore', { time_spent_s: 0 }));
    return result;
  }

  async function myIonMetricSetAppUseTimeIgnore(time_spent_s: number) {
    await myIonStoreWrite(APP_USE_TIME + '_ignore', JSON.stringify({ time_spent_s: time_spent_s }));
  }

  return (
    <AppUseTimeContext.Provider
      value={{
        //
        Helloworld,
        myIonMetricGetAppUseTime,
        myIonMetricResetAppUseTime,
        myIonMetricIncAppUseTime,
        //
        myIonMetricSetAppUseTime,
        myIonMetricGetAppUseTimeIgnore,
        myIonMetricSetAppUseTimeIgnore
      }}
    >
      {/*  */}
      {children}
    </AppUseTimeContext.Provider>
  );
};

export const useAppUseTime = (): AppUseTimeContextProps => {
  const context = useContext(AppUseTimeContext);
  if (!context) {
    throw new Error('useAppUseTime must be used within a AppUseTimeProvider');
  }
  return context;
};

interface AppUseTimeContextProps {
  Helloworld: () => void;
  myIonMetricGetAppUseTime: () => Promise<{ time_spent_s: number }>;
  myIonMetricIncAppUseTime: (time_spent_s: number) => Promise<void>;
  myIonMetricResetAppUseTime: () => Promise<void>;
  //
  myIonMetricSetAppUseTime: (time_spent_s: number) => Promise<void>;
  myIonMetricGetAppUseTimeIgnore: () => Promise<{ time_spent_s: number }>;
  myIonMetricSetAppUseTimeIgnore: (time_spent_s: number) => Promise<void>;
}
