package com.gh.gamecenter.download

import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.gh.common.util.HomePluggableHelper
import com.gh.common.util.PackageInstaller
import com.gh.download.DownloadManager
import com.gh.gamecenter.DownloadManagerActivity
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.fragment.BaseFragment_TabLayout
import com.gh.gamecenter.common.eventbus.EBMiPush
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.visibleIf
import com.gh.gamecenter.databinding.TabItemDownloadNumberBinding
import com.gh.gamecenter.entity.HomePluggableFilterEntity
import com.gh.gamecenter.entity.PluginLocation
import com.gh.gamecenter.eventbus.EBDownloadChanged
import com.gh.gamecenter.eventbus.EBSkip
import com.gh.gamecenter.eventbus.EBUISwitch
import com.gh.gamecenter.manager.PackagesManager
import com.lightgame.download.DownloadStatus
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class DownloadFragment : BaseFragment_TabLayout() {

    // 下载 tab 是否被手动选中过
    private var mIsDownloadTabHasBeenSelected: Boolean = false
    private var mIsUpdateTabHasBeenSelected: Boolean = false

    private lateinit var mDownloadNumberTv: TextView
    private lateinit var mUpdateNumberTv: TextView
    private val mDownloadManager: DownloadManager by lazy { DownloadManager.getInstance() }

    private var mPermanentInactivePluggableApkList: List<HomePluggableFilterEntity>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mPermanentInactivePluggableApkList = HomePluggableHelper.getPermanentInactivePluggablePackage()
    }

    override fun initFragmentList(fragments: MutableList<Fragment>) {
        fragments.add(GameDownloadFragment())
        fragments.add(UpdatableGameFragment())
        fragments.add(NewInstalledGameFragment())
    }

    override fun initTabTitleList(tabTitleList: MutableList<String>) {
        tabTitleList.add(getString(R.string.download_game))
        tabTitleList.add(getString(R.string.download_tab_update))
        tabTitleList.add(getString(R.string.download_tab_installed))
    }

    override fun provideTabView(position: Int, tabTitle: String): View? {
        val viewBinding = TabItemDownloadNumberBinding.inflate(LayoutInflater.from(context))
        var view: View? = viewBinding.root
        viewBinding.tabTitle.text = tabTitle

        when (position) {
            INDEX_DOWNLOAD -> mDownloadNumberTv = viewBinding.tabDownloadNumber
            INDEX_UPDATE -> mUpdateNumberTv = viewBinding.tabDownloadNumber
            else -> view = null
        }
        return view
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        setNavigationTitle(getString(R.string.title_downloadmanager))
    }

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

        updateUpdateHint()
        updateDownloadHint()

        if (mDownloadNumberTv.visibility != View.VISIBLE && mUpdateNumberTv.visibility == View.VISIBLE) {
            mViewPager.currentItem = INDEX_UPDATE
        } else {
            // 进入并选中下载管理时立马标记已下载待安装为已读
            mIsDownloadTabHasBeenSelected = true
            updateDownloadHint()
            mDownloadManager.markDownloadingTaskAsRead()
            mDownloadManager.markDownloadedTaskAsRead()
        }

        val pathOfPackageToInstall = activity?.intent?.getStringExtra(KEY_PATH_OF_PACKAGE_TO_INSTALL)
        if (!TextUtils.isEmpty(pathOfPackageToInstall)) {
            PackageInstaller.install(requireContext(), false, pathOfPackageToInstall)
        }
    }

    override fun onResume() {
        super.onResume()

        if (mViewPager.currentItem == INDEX_DOWNLOAD) {
            mDownloadManager.markDownloadingTaskAsRead()
            mDownloadManager.markDownloadedTaskAsRead()
            updateDownloadHint()
        }
        DownloadManager.getInstance().checkAndRetryDownload()
    }

    override fun onParentActivityFinish() {
        super.onParentActivityFinish()

        // onDestroy 的回调有点晚，不能及时更新外部红点
        if (mIsDownloadTabHasBeenSelected || mViewPager.currentItem == INDEX_DOWNLOAD) {
            mDownloadManager.markDownloadingTaskAsRead()
            mDownloadManager.markDownloadedTaskAsRead()
        }
    }

    override fun onPageSelected(index: Int) {
        EventBus.getDefault().post(EBUISwitch(DownloadManagerActivity.TAG, index))

        if (index == INDEX_UPDATE) {
            mIsUpdateTabHasBeenSelected = true
            updateUpdateHint()
            mDownloadManager.markUpdatableTaskAsRead()
        } else if (index == INDEX_DOWNLOAD) {
            mIsDownloadTabHasBeenSelected = true
            updateDownloadHint()
            mDownloadManager.markDownloadingTaskAsRead()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(mipush: EBMiPush) {
        if ("plugin_install" == mipush.from) {
            mViewPager.currentItem = DownloadManagerActivity.INDEX_DOWNLOAD
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(changed: EBDownloadChanged) {
        if ("download" == changed.type) {
            // 因为数据库已安装的数据是是比这个回调晚的，所以这里延时500ms
            postDelayedRunnable({ updateDownloadHint() }, 500L)
        } else if ("update" == changed.type) {
            updateUpdateHint()
        }
    }

    private fun updateDownloadHint() {
        if (!::mDownloadNumberTv.isInitialized || !isAdded) return

        val downloadData = DownloadManager.getInstance().allDownloadEntityExcludeSilentTask
        if (downloadData.size > 0) {
            mDownloadNumberTv.visibility = View.VISIBLE
        } else {
            mDownloadNumberTv.visibility = View.INVISIBLE
            return
        }

        var downloadingCount = 0
        for (download in downloadData) {
            if (DownloadStatus.done != download.status) {
                downloadingCount++
            }
        }

        val layoutParams = mDownloadNumberTv.layoutParams as LinearLayout.LayoutParams
        when {
            downloadingCount > 0 -> {
                layoutParams.width = ViewGroup.LayoutParams.WRAP_CONTENT
                layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT
                layoutParams.setMargins(4F.dip2px(), 0, 0, 0F.dip2px())
                mDownloadNumberTv.setBackgroundColor(Color.TRANSPARENT)
                mDownloadNumberTv.text = downloadingCount.toString()
            }
            mDownloadManager.isContainsUnreadDownloadedTask -> {
                layoutParams.width = 6F.dip2px()
                layoutParams.height = 6F.dip2px()
                layoutParams.setMargins(2F.dip2px(), 0, 0, 3F.dip2px())
                mDownloadNumberTv.setBackgroundResource(R.drawable.oval_hint_red_bg)
                mDownloadNumberTv.text = ""
            }
            else -> mDownloadNumberTv.visibility = View.GONE
        }
        mDownloadNumberTv.layoutParams = layoutParams
    }

    private fun updateUpdateHint() {
        if (!::mUpdateNumberTv.isInitialized) return

        if (mIsUpdateTabHasBeenSelected) {
            mUpdateNumberTv.visibility = View.INVISIBLE
            return
        }

        val updateCount = mDownloadManager.getUnreadUpdateCount(PackagesManager.getUpdateList()
            .filter { gameUpdateEntity ->
                gameUpdateEntity.isShowPlugin(PluginLocation.only_index)
                        && mPermanentInactivePluggableApkList?.filter { it.pkgName == gameUpdateEntity.packageName }?.size == 0
            })

        mUpdateNumberTv.visibleIf(updateCount != 0)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(skip: EBSkip) {
        if (DownloadManagerActivity.TAG == skip.type) {
            if (view != null) {
                requireView().postDelayed({
                    mViewPager.currentItem = skip.currentItem
                    if (isAdded && skip.currentItem == DownloadManagerActivity.INDEX_DOWNLOAD) {
                        val fragments = childFragmentManager.fragments
                        if (fragments != null) {
                            for (fragment in fragments) {
                                if (fragment.isAdded
                                    && fragment is GameDownloadFragment
                                ) {
                                    fragment.onResume() // auto refresh list
                                }
                            }
                        }
                    }
                }, 300)
            }
        }
    }

    companion object {
        const val INDEX_DOWNLOAD = 0
        const val INDEX_UPDATE = 1

        const val KEY_PATH_OF_PACKAGE_TO_INSTALL = "key_path_of_package_to_install"
    }

}