import React, { createContext, useContext, useRef, useEffect } from 'react';
import JamClientProxy from '../jamClientProxy';

import { FakeJamClientProxy } from '../fakeJamClientProxy';
import { FakeJamClientRecordings } from '../fakeJamClientRecordings';
import { FakeJamClientMessages } from '../fakeJamClientMessages';
import { useJamKazamApp } from './JamKazamAppContext';
import { useGlobalContext } from './GlobalContext';

const JamClientContext = createContext(null);

export const JamClientProvider = ({ children }) => {
  //assign an instance of JamClientProxy to a ref so that it persists across renders
  //if development environment, use FakeJamClientProxy
  //otherwise use JamClientProxy
  //initialize the proxy when the provider is mounted
  //and provide it to the context value

  //get the app instance from JamKazamAppContext
  const app = useJamKazamApp();
  const { globalObject } = useGlobalContext();

  const proxyRef = useRef(null);

  if (process.env.NODE_ENV === 'test' || process.env.REACT_APP_USE_FAKE_CLIENT === 'true') {
    const fakeJamClientMessages = new FakeJamClientMessages();
    const proxy = new FakeJamClientProxy(app, fakeJamClientMessages); // Pass appropriate parameters
    proxyRef.current = proxy.init();
    // For testing purposes, we can add some fake recordings
    const fakeJamClientRecordings = new FakeJamClientRecordings(app, proxyRef.current, fakeJamClientMessages);
    proxyRef.current.SetFakeRecordingImpl(fakeJamClientRecordings);
  } else {
    if (!proxyRef.current) {
      const proxy = new JamClientProxy(app, console, globalObject);
      proxyRef.current = proxy.init();
    }
  }

  if (!proxyRef.current) {
    const proxy = new JamClientProxy(app, console, globalObject);
    proxyRef.current = proxy.init();
  }
  window.jamClient = proxyRef.current; // TODO: Expose jamClient globally for debugging. This is temporarily added. Remove it later.

  // Register metronome callback with jamClient when it's available
  useEffect(() => {
    if (proxyRef.current && proxyRef.current.setMetronomeOpenCallback) {
      console.log('Registering metronome callback with jamClient');
      proxyRef.current.setMetronomeOpenCallback("JK.HandleMetronomeCallback2");
    }
  }, [proxyRef.current]);

  return (
    <JamClientContext.Provider value={proxyRef.current}>
      {children}
    </JamClientContext.Provider>
  );
};

export const useJamClient = () => useContext(JamClientContext);
