package com.doverfuelingsolutions.issp.view.fragment

import android.view.LayoutInflater
import android.view.View
import androidx.annotation.StringRes
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.AppCompatTextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.lifecycleScope
import com.doverfuelingsolutions.issp.R
import com.doverfuelingsolutions.issp.view.widget.FragmentToolbar
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.doverfuelingsolutions.issp.utils.StringUtil
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

abstract class FragmentBasic : Fragment() {

    private var basicDialog: AlertDialog? = null
    private var displayAfterDelay = false

    private var mToolbar: FragmentToolbar? = null

    fun setToolBar(toolbar: FragmentToolbar) {
        mToolbar = toolbar
        toolbar.setBackHandler { back() }
        toolbar.setOnCountdownFinish { home() }
        toolbar.setHomeHandler { home() }
    }

    fun loading(@StringRes string: Int) = loading(StringUtil.get(string))
    private fun loading(msg: String) {
        displayAfterDelay = true
        lifecycleScope.launch {
            // 避免异步响应过快造成闪屏
            delay(500)
            // 在 delay 时，可能已手动关闭
            if (displayAfterDelay) {
                mToolbar?.pauseCountdown()

                val view = LayoutInflater.from(requireContext()).inflate(R.layout.fragment_loading, null)
                view.findViewById<AppCompatTextView>(R.id.loadingTip)?.text = msg
                basicDialog = MaterialAlertDialogBuilder(requireContext())
                    .setCancelable(false)
                    .setView(view)
                    .show()
            }
        }
    }

    fun hideLoading() {
        mToolbar?.resumeCountdown()

        displayAfterDelay = false
        basicDialog?.let {
            if (isVisible) it.dismiss()
        }
    }

    fun home() {
        val fragmentManager = requireActivity().supportFragmentManager
        val deep = fragmentManager.backStackEntryCount
        if (deep > 0)
            fragmentManager.popBackStack(
                fragmentManager.getBackStackEntryAt(0).id,
                FragmentManager.POP_BACK_STACK_INCLUSIVE
            )
    }

    fun back() {
        requireActivity().supportFragmentManager.popBackStack()

    }
}