import { createContext, useContext, useEffect, useState } from "react";
import { Drivers, Storage } from "@ionic/storage";

const store = new Storage({
  name: "__mydb",
  driverOrder: [Drivers.IndexedDB, Drivers.LocalStorage],
});

export const StoreContext = createContext({
  helloworld: "",
  setHelloworld: (_: string) => {},
  myIonStoreRead: async (_: string): Promise<string | null> => null,
  myIonStoreWrite: async (_: string, __: string): Promise<void> => {},
});

export const StoreProvider = ({ children }: any) => {
  const [helloworld, setHelloworld] = useState("helloworld");

  async function myIonStoreRead(key: string) {
    const name = await store.get(key);
    return name;
  }

  async function myIonStoreWrite(key: string, value: string) {
    const name = await store.set(key, value);
  }

  useEffect(() => {
    const initializeStore = async () => {
      await store.create();
      console.log("create store done");
    };
    initializeStore();
  }, []);

  return (
    <StoreContext.Provider
      value={{
        helloworld,
        setHelloworld,
        myIonStoreRead,
        myIonStoreWrite,
      }}
    >
      {children}
    </StoreContext.Provider>
  );
};

export function useMyIonStore() {
  let { myIonStoreRead, myIonStoreWrite } = useContext(StoreContext);
  return { myIonStoreRead, myIonStoreWrite };
}
