package com.ez.ertc.meeting.utils;

import android.content.Intent;
import android.util.SparseArray;

import androidx.fragment.app.Fragment;

import com.ez.ertc.meeting.utils.ActivityLauncher.Callback;

import java.security.SecureRandom;

public class RouterFragment  extends Fragment {
    private SparseArray<Callback> mCallbacks = new SparseArray();
    private SecureRandom mCodeGenerator = new SecureRandom();

    public RouterFragment() {
    }

    public static RouterFragment newInstance() {
        return new RouterFragment();
    }

    public void startActivityForResult(Intent intent, Callback callback) {
        int requestCode = this.makeRequestCode();
        this.mCallbacks.put(requestCode, callback);
        this.startActivityForResult(intent, requestCode);
    }

    private int makeRequestCode() {
        int tryCount = 0;

        int requestCode;
        do {
            requestCode = this.mCodeGenerator.nextInt(65535);
            ++tryCount;
        } while(this.mCallbacks.indexOfKey(requestCode) >= 0 && tryCount < 10);

        return requestCode;
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Callback callback = (Callback)this.mCallbacks.get(requestCode);
        this.mCallbacks.remove(requestCode);
        if (callback != null) {
            callback.onActivityResult(resultCode, data);
        }

    }
}
