package com.gh.gamecenter.common.avoidcallback

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import io.reactivex.Observable


class AvoidOnResultManager {
    val TAG = "AvoidOnResultManager"
    private var mAvoidOnResultFragment: AvoidOnResultFragment

    private constructor(activity: AppCompatActivity) {
        mAvoidOnResultFragment = getAvoidOnResultFragment(activity)
    }

    private constructor(fragment: Fragment) : this(fragment.activity as AppCompatActivity)

    companion object {
        fun getInstance(activity: AppCompatActivity): AvoidOnResultManager {
            return AvoidOnResultManager(activity)
        }

        fun getInstance(fragment: Fragment): AvoidOnResultManager {
            return AvoidOnResultManager(fragment)
        }
    }

    private fun getAvoidOnResultFragment(activity: AppCompatActivity): AvoidOnResultFragment {
        var avoidOnResultFragment = findAvoidOnResultFragment(activity)
        if (avoidOnResultFragment == null) {
            avoidOnResultFragment = AvoidOnResultFragment()
            val fragmentManager = activity.supportFragmentManager
            fragmentManager
                .beginTransaction()
                .add(avoidOnResultFragment, TAG)
                .commitAllowingStateLoss()
            fragmentManager.executePendingTransactions()
        }
        return avoidOnResultFragment
    }

    private fun findAvoidOnResultFragment(activity: AppCompatActivity): AvoidOnResultFragment? {
        return activity.supportFragmentManager.findFragmentByTag(TAG) as? AvoidOnResultFragment
    }

    fun startForResult(intent: Intent, callback: Callback) {
        mAvoidOnResultFragment.startForResult(intent, callback)
    }

    fun startForResult(clazz: Class<*>, callback: Callback) {
        val intent = Intent(mAvoidOnResultFragment.activity, clazz)
        mAvoidOnResultFragment.startForResult(intent, callback)
    }

    fun startForResult(intent: Intent): Observable<ActivityResultInfo> {
        return mAvoidOnResultFragment.startForResult(intent)
    }

    fun startForResult(clazz: Class<*>): Observable<ActivityResultInfo> {
        val intent = Intent(mAvoidOnResultFragment.activity, clazz)
        return mAvoidOnResultFragment.startForResult(intent)
    }
}