package com.gh.common.fragment

import androidx.fragment.app.FragmentManager
import java.lang.reflect.Field

fun FragmentManager.popBackStackAllowStateLoss() {
    popBackStackAllowStateLoss(-1, 0)
}

fun FragmentManager.popBackStackAllowStateLoss(id: Int, flags: Int) {
    if (!isStateSaved) {
        popBackStack(id, flags)
    }
}

fun FragmentManager.popBackStackAllowStateLoss(name: String?, flags: Int) {
    if (!isStateSaved) {
        popBackStack(name, flags)
    }
}

fun FragmentManager.popBackStackImmediateAllowStateLoss() = popBackStackAllowStateLoss(-1, 0)

fun FragmentManager.popBackStackImmediateAllowStateLoss(id: Int, flags: Int) =
    if (!isStateSaved) {
        popBackStackImmediate(id, flags)
    } else {
        false
    }

@Throws(NoSuchFieldException::class)
private fun getField(clazz: Class<*>, name: String): Field {
    var cls: Class<*>? = clazz
    while (cls != null) {
        try {
            val declaredField = cls.getDeclaredField(name)
            declaredField.isAccessible = true
            return declaredField
        } catch (e: NoSuchFieldException) {
            e.printStackTrace()
        }
        cls = cls.superclass
    }
    throw NoSuchFieldException()
}