// Copyright (C) 2025 Acoustic, L.P. All rights reserved.
//
// NOTICE: This file contains material that is confidential and proprietary to
// Acoustic, L.P. and/or other developers. No license is granted under any intellectual or
// industrial property rights of Acoustic, L.P. except as may be provided in an agreement with
// Acoustic, L.P. Any unauthorized copying or distribution of content from this file is
// prohibited.
//
//
//  Created by Omar Hernandez on 5/9/25.
//

package com.acousticconnectrn;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.annotation.NonNull;

import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.module.model.ReactModuleInfoProvider;
import com.facebook.react.TurboReactPackage;
import com.margelo.nitro.NitroModules;
import com.margelo.nitro.acousticconnectrn.AcousticConnectRNOnLoad;

import java.util.HashMap;

public class AcousticConnectRNPackage extends TurboReactPackage {
  @Nullable
  @Override
  public NativeModule getModule(@NonNull String name, @NonNull ReactApplicationContext reactContext) {
    return null;
  }

  @NonNull
  @Override
  public ReactModuleInfoProvider getReactModuleInfoProvider() {
    return HashMap::new;
  }

  static {
    AcousticConnectRNOnLoad.initializeNative();
    try {
      // Start a background thread to wait for the context
      new Thread(() -> {
        ReactApplicationContext reactContext = null;

        // Poll until NitroModules.getApplicationContext() is not null
        while (reactContext == null) {
          reactContext = NitroModules.getApplicationContext();
          if (reactContext == null) {
            try {
              Thread.sleep(100); // Sleep for 100ms before checking again
            } catch (InterruptedException e) {
              Log.e("AcousticConnectRNPackage", "Thread interrupted while waiting for ReactApplicationContext.", e);
              return;
            }
          }
        }

        // Post initialization logic to the main (UI) thread
        ReactApplicationContext finalReactContext = reactContext;
        new Handler(Looper.getMainLooper()).post(() -> {
          HybridAcousticConnectRN hybridInstance = new HybridAcousticConnectRN(finalReactContext);
          Log.i("AcousticConnectRNPackage", "HybridAcousticConnectRN initialized successfully.");
        });
      }).start();
    } catch (Exception e) {
      Log.e("AcousticConnectRNPackage", "Failed to initialize HybridAcousticConnectRN.", e);
    }
  }
}
