import {type JSX, ParentComponent, createSignal, onMount, createResource, Show} from "solid-js";
import {BrowserProxy as BrowserProxyNS} from "../../../types/browser_proxy";
import {ServiceRootProvider, useServices} from "./ServiceRootProvider";
import {BrowserProxyProvider} from "./BrowserProxyProvider";
import {GlobalStyle} from "../components/ui/GlobalStyle";
import {getQueryClient, initCustomCachePersistence} from "../util/query-client";
import {QueryClientProvider} from "@tanstack/solid-query";
import { IPreferencesService } from "src/business-layer/services/services";

interface AppProvidersProps {
  browserProxy: BrowserProxyNS.IBrowserProxyConstructor;
  children?: JSX.Element;
}

export const AppProviders: ParentComponent<AppProvidersProps> = props => {
  const queryClient = getQueryClient();

  return (
    <BrowserProxyProvider proxy={props.browserProxy}>
      <ServiceRootProvider browserProxy={props.browserProxy}>
        <PersistenceGate queryClient={queryClient}>{props.children}</PersistenceGate>
      </ServiceRootProvider>
    </BrowserProxyProvider>
  );
};

const PersistenceGate: ParentComponent<{queryClient: any}> = props => {
  const services = useServices();
  const [ready, setReady] = createSignal(false);
  onMount(async () => {
    await initCustomCachePersistence(services.preferences)
    setReady(true)
  })
  console.log("🟢 PersistenceGate: Rendering, ready() =", ready());

  return (
    <Show
      when={ready()}
      fallback={
        <div class="flex items-center justify-center min-h-screen">
          <div>Loading... {`${ready()}`}</div>
        </div>
      }>
      <QueryClientProvider client={props.queryClient}>
        <GlobalStyle />
        {props.children}
      </QueryClientProvider>
    </Show>
  );
};
