package com.gh.vspace

import android.animation.ValueAnimator
import android.os.Bundle
import android.view.View
import android.view.animation.DecelerateInterpolator
import com.gh.download.DownloadManager
import com.gh.gamecenter.common.base.fragment.BaseFragment
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.databinding.FragmentVspaceLoadingBinding
import com.gh.gamecenter.feature.entity.GameEntity
import com.lightgame.download.DataWatcher
import com.lightgame.download.DownloadEntity
import com.lightgame.download.DownloadStatus.*
import com.lightgame.utils.Utils

class VSpaceLoadingFragment : BaseFragment<Any>() {

    private var mIsInstallation = false
    private var mGame: GameEntity? = null
    private val mBinding: FragmentVspaceLoadingBinding by lazy {
        FragmentVspaceLoadingBinding.inflate(
            layoutInflater
        )
    }
    private val mDataWatcher by lazy {
        object : DataWatcher() {
            override fun onDataChanged(downloadEntity: DownloadEntity?) {
                if (downloadEntity == null) return
                if (downloadEntity.gameId != mGame?.id) return

                when (downloadEntity.status) {
                    add,
                    download,
                    downloading -> {
                        mBinding.progressBar.progress = downloadEntity.percent.toInt()
                        mBinding.progressTv.text = "加载中...${downloadEntity.percent}%"
                    }

                    done -> {
                        mBinding.progressBar.progress = 100
                        mBinding.progressTv.text = "启动中...${downloadEntity.percent}%"
                    }

                    pause,
                    delete,
                    timeout,
                    hijack,
                    notfound,
                    neterror,
                    diskisfull,
                    diskioerror,
                    overflow -> requireActivity().finish()
                    unqualified -> {
                        ToastUtils.toast("暂不支持未成年人下载")
                        requireActivity().finish()
                    }
                    uncertificated -> {
                        ToastUtils.toast("未实名，暂不支持下载")
                        requireActivity().finish()
                    }
                    unavailable -> {
                        ToastUtils.toast("该游戏未接入防沉迷系统，暂不支持下载")
                        requireActivity().finish()
                    }

                    else -> {
                        // do nothing
                    }
                }
            }
        }
    }

    override fun getLayoutId() = 0
    override fun getInflatedLayout() = mBinding.root

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mGame = arguments?.get(EntranceConsts.KEY_DATA) as GameEntity?
        mIsInstallation = arguments?.get(VSpaceLoadingActivity.IS_INSTALLATION) as? Boolean ?: true
        mGame?.let { initView(it, mBinding) }

        // 安装状态显示虚假的进度动画
        if (mIsInstallation) {
            showFakeInstallationProgress(mBinding)
        }

        VHelper.mPackageInstalledLiveData.observe(viewLifecycleOwner) {
            val currentPackageName = mGame?.getApk()?.firstOrNull()?.packageName
            if (it == currentPackageName) {
                VHelper.launch(requireActivity(), currentPackageName!!)
            }
        }
        VHelper.mVSpaceLoadingCloseLiveData.observe(viewLifecycleOwner) {
            if (it == true) {
                activity?.let {
                    if(!it.isFinishing) {
                        it.finish()
                    }
                }
            }
        }
    }

    private fun initView(gameEntity: GameEntity, binding: FragmentVspaceLoadingBinding) {
        binding.gameIconIv.displayGameIcon(gameEntity)
        binding.hideLoadingContainer.setOnClickListener { requireActivity().finish() }
        binding.nameTv.text = gameEntity.name
    }

    private fun showFakeInstallationProgress(binding: FragmentVspaceLoadingBinding) {
        ValueAnimator.ofInt(0, 99).apply {
            duration = 10000L
            interpolator = DecelerateInterpolator()
            addUpdateListener {
                if (!isAdded) {
                    removeAllUpdateListeners()
                    return@addUpdateListener
                }

                val progress = it.animatedValue as Int
                binding.progressBar.progress = progress
                binding.progressTv.text = "启动中${progress}%"
            }
        }.start()
    }

    override fun onResume() {
        super.onResume()

        if (!mIsInstallation) {
            DownloadManager.getInstance().addObserver(mDataWatcher)
        }
    }

    override fun onPause() {
        super.onPause()

        if (!mIsInstallation) {
            DownloadManager.getInstance().removeObserver(mDataWatcher)
        }
    }

}