package com.gh.gamecenter.common.avoidcallback

import android.content.Intent
import android.os.Bundle
import android.util.SparseArray
import androidx.fragment.app.Fragment
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject

class AvoidOnResultFragment : Fragment() {
    private val mSubjects = SparseArray<PublishSubject<ActivityResultInfo>>()
    private val mCallbacks = SparseArray<Callback>()

    private var requestCode = 1000

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        retainInstance = true
    }

    fun startForResult(intent: Intent): Observable<ActivityResultInfo> {
        val subject = PublishSubject.create<ActivityResultInfo>()
        return subject.doOnSubscribe {
            mSubjects.put(requestCode, subject)
            startActivityForResult(intent, requestCode)
            requestCode++
        }
    }

    fun startForResult(intent: Intent, callback: Callback) {
        mCallbacks.put(requestCode, callback)
        startActivityForResult(intent, requestCode)
        requestCode++
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        val subject = mSubjects.get(requestCode)
        if (subject != null) {
            subject.onNext(ActivityResultInfo(resultCode, data))
            subject.onComplete()
        }
        mSubjects.remove(requestCode)
        val callback = mCallbacks.get(requestCode)
        callback?.onActivityResult(resultCode, data)
        mCallbacks.remove(requestCode)
    }
}