package com.gh.download.dialog

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.FragmentActivity
import com.gh.gamecenter.common.base.fragment.BaseDialogFragment
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.BuildConfig
import com.gh.gamecenter.common.utils.loadDataCompat
import com.gh.gamecenter.databinding.DialogDownloadLinkBinding
import com.gh.gamecenter.feature.entity.GameEntity
import com.halo.assistant.HaloApp
import com.lightgame.utils.AppManager


class DownloadLinkDialog : BaseDialogFragment() {

    private var mLinkEntity: GameEntity.PluginLink? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mLinkEntity = requireArguments().getParcelable(KEY_LINK_ENTITY)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        val binding: DialogDownloadLinkBinding = DialogDownloadLinkBinding.inflate(layoutInflater, container, false)
        binding.title.text = mLinkEntity?.title
        binding.webView.loadDataCompat(mLinkEntity?.content ?: "")

        binding.confirm.setOnClickListener {
            dismissAllowingStateLoss()
        }
        return binding.root
    }

    override fun onStart() {
        super.onStart()
        val width = HaloApp.getInstance().application.resources.displayMetrics.widthPixels
        val height = dialog?.window?.attributes?.height ?: ViewGroup.LayoutParams.WRAP_CONTENT
        dialog?.window?.setLayout(width - 60F.dip2px(), height)
    }

    companion object {
        const val KEY_LINK_ENTITY = "link_entity"

        @JvmStatic
        fun showDownloadDialog(context: Context?, linkEntity: GameEntity.PluginLink) {
            val fragmentActivity: FragmentActivity = if (context is FragmentActivity) {
                context
            } else if (BuildConfig.DEBUG) {
                throw IllegalStateException("DownloadLinkDialog context must be FragmentActivity")
            } else {
                val currentActivity = AppManager.getInstance().currentActivity()
                if (currentActivity is FragmentActivity) {
                    currentActivity
                } else {
                    throw IllegalStateException("current activity context must be FragmentActivity")
                }
            }

            val dialog = DownloadLinkDialog().apply {
                arguments = Bundle().apply {
                    putParcelable(KEY_LINK_ENTITY, linkEntity)
                }
            }
            dialog.show(fragmentActivity.supportFragmentManager, DownloadLinkDialog::class.java.name)
        }
    }
}