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

const FullmarkCountContext = createContext<FullmarkCountContextProps | undefined>(undefined);

export const FullmarkCountProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const { myIonStoreRead, myIonStoreWrite } = useMyIonMetric();
  function Helloworld() {
    console.log('helloworld');
  }

  async function myIonMetricGetFullMarkCount() {
    let result = JSON.parse(await myIonStoreRead(FULLMARK_COUNT_KEY, { count: 0 }));
    return result;
  }

  async function myIonMetricResetFullMarkCount() {
    await myIonStoreWrite(FULLMARK_COUNT_KEY, JSON.stringify({ count: 0 }));
  }

  async function myIonMetricIncFullMarkCount() {
    let result = await myIonMetricGetFullMarkCount();
    await myIonStoreWrite(FULLMARK_COUNT_KEY, JSON.stringify({ count: result.count + 1 }));
  }

  async function myIonMetricSetFullMarkCount(num: number) {
    await myIonStoreWrite(FULLMARK_COUNT_KEY, JSON.stringify({ count: num }));
  }

  async function myIonMetricSetFullMarkIgnore(num: number) {
    await myIonStoreWrite(FULLMARK_IGNORE_COUNT, JSON.stringify({ count: num }));
  }
  async function myIonMetricGetFullMarkIgnore() {
    let result = JSON.parse(await myIonStoreRead(FULLMARK_IGNORE_COUNT, { count: 0 }));
    return result;
  }

  return (
    <FullmarkCountContext.Provider
      value={{
        Helloworld,
        myIonMetricGetFullMarkCount,
        myIonMetricResetFullMarkCount,
        myIonMetricIncFullMarkCount,
        //
        myIonMetricSetFullMarkCount,
        myIonMetricSetFullMarkIgnore,
        myIonMetricGetFullMarkIgnore
      }}
    >
      {/*  */}
      {children}
    </FullmarkCountContext.Provider>
  );
};

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

interface FullmarkCountContextProps {
  Helloworld: () => void;
  //
  // FullMark
  myIonMetricGetFullMarkCount: () => Promise<{ count: number }>;
  myIonMetricResetFullMarkCount: () => Promise<void>;
  myIonMetricIncFullMarkCount: () => Promise<void>;
  //
  myIonMetricSetFullMarkCount: (num: number) => Promise<void>;
  myIonMetricSetFullMarkIgnore: (num: number) => Promise<void>;
  myIonMetricGetFullMarkIgnore: () => Promise<{ count: number }>;
}
