package com.gh.download.simple

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager

class AutoUnregisteredSimpleDownloadListener(var id: String, fragment: Fragment, var listener: DownloadListener) {
    init {
        fragment.parentFragmentManager.registerFragmentLifecycleCallbacks(
            object : FragmentManager.FragmentLifecycleCallbacks() {
                override fun onFragmentViewDestroyed(fm: FragmentManager, f: Fragment) {
                    super.onFragmentViewDestroyed(fm, f)
                    if (f === fragment) {
                        DownloadMessageHandler.unregisterListener(id, listener)
                        fragment.parentFragmentManager.unregisterFragmentLifecycleCallbacks(this)
                    }
                }
            }, false
        )
        DownloadMessageHandler.registerListener(id, listener)
    }

    fun unregisteredListener() {
        DownloadMessageHandler.unregisterListener(id, listener)
    }
}