package com.atmob.voiceai.utils;


import androidx.activity.ComponentActivity;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.ActivityResultRegistry;
import androidx.activity.result.contract.ActivityResultContract;
import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.LifecycleOwner;

import java.util.UUID;

public class ActivityForResultUtil<I, O> {


    ActivityResultLauncher<I> launcher = null;


    public void startActivityForResult(ComponentActivity activity, ActivityResultContract<I, O> contract, I input, ActivityResultCallback<O> callback) {
        String key = UUID.randomUUID().toString();

        ActivityResultRegistry registry = activity.getActivityResultRegistry();
        LifecycleEventObserver observer = new LifecycleEventObserver() {

            @Override
            public void onStateChanged(@NonNull LifecycleOwner lifecycleOwner, @NonNull Lifecycle.Event event) {
                if (Lifecycle.Event.ON_DESTROY == event) {
                    if (launcher != null) {
                        launcher.unregister();
                    }
                    activity.getLifecycle().removeObserver(this);
                }
            }
        };
        activity.getLifecycle().addObserver(observer);

        launcher = registry.register(key, contract, result -> {
            if (launcher != null) {
                launcher.unregister();
            }
            activity.getLifecycle().removeObserver(observer);
            callback.onActivityResult(result);
        });
        launcher.launch(input);
    }
}
