package com.gh.common.util

import android.app.Dialog
import android.content.Context
import android.view.View
import android.view.Window
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.gh.download.simple.AutoUnregisteredSimpleDownloadListener
import com.gh.download.simple.DownloadListener
import com.gh.gamecenter.R
import com.gh.gamecenter.cloudarchive.BaseCloudArchiveViewModel
import com.gh.gamecenter.common.eventbus.EBReuse
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.runOnUiThread
import com.gh.gamecenter.core.utils.DisplayUtils
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.databinding.DialogArchiveLoadingBinding
import com.gh.gamecenter.entity.ArchiveEntity
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.retrofit.RetrofitManager
import com.gh.gamecenter.va.VCore
import com.gh.vspace.VArchiveHelper
import com.gh.vspace.VHelper
import com.gh.vspace.VHelper.is32
import com.lg.download.DownloadError
import com.lg.download.DownloadStatus
import io.reactivex.schedulers.Schedulers
import org.greenrobot.eventbus.EventBus
import splitties.systemservices.layoutInflater

/**
 * 云存档下载按钮辅助类
 */
object ArchiveDownloadButtonHelper {

    fun bindItem(
        context: Context,
        entrance: String,
        fragment: Fragment,
        packageName: String,
        viewModel: BaseCloudArchiveViewModel,
        archiveEntity: ArchiveEntity,
        downloadBtn: TextView,
        gameEntity: GameEntity?,
        downloadCompletedListener: (() -> Unit)? = null
    ) {
        downloadBtn.text = if (VArchiveHelper.isArchiveDownloaded(archiveEntity.md5)) {
            R.string.archive_apply.toResString()
        } else {
            R.string.archive_download.toResString()
        }
        downloadBtn.setOnClickListener {
            when {
                // 检查是否已安装游戏
                !VHelper.isInstalled(packageName) -> {
                    // 检查游戏是否在安装中
                    if (!VHelper.isInstalling(packageName)) {
                        showDownloadTipDialog(context)
                    } else {
                        ToastUtils.toast("游戏正在安装中，请稍候")
                    }
                }
                // 检查本地是否已下载存档
                VArchiveHelper.isArchiveDownloaded(archiveEntity.md5) -> viewModel.getArchiveConfigString {
                    showApplyArchiveTipDialog(
                        context,
                        entrance,
                        packageName,
                        it,
                        archiveEntity,
                        gameEntity
                    )
                }
                // 检查完毕下载存档
                else -> downloadArchive(
                    context,
                    entrance,
                    fragment,
                    packageName,
                    viewModel,
                    archiveEntity,
                    downloadBtn,
                    gameEntity,
                    downloadCompletedListener
                )
            }
        }
    }

    private fun showVSpaceTipDialog(context: Context, gameEntity: GameEntity?) {
        NewFlatLogUtils.logCloudArchiveVSpaceDownloadDialogShow()
        DialogHelper.showDialog(
            context,
            R.string.archive_dialog_title.toResString(),
            R.string.archive_vspace_dialog_content.toResString(),
            R.string.archive_vspace_dialog_confirm.toResString(),
            com.gh.gamecenter.common.R.string.cancel.toResString(),
            {
                NewFlatLogUtils.logCloudArchiveVSpaceDownloadDialogClick(R.string.archive_vspace_dialog_confirm.toResString())
                VHelper.showVSpaceDialog(context, gameEntity)
            },
            {
                NewFlatLogUtils.logCloudArchiveVSpaceDownloadDialogClick(com.gh.gamecenter.common.R.string.cancel.toResString())
            },
            extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
        )
    }

    private fun showDownloadTipDialog(context: Context) {
        NewFlatLogUtils.logCloudArchiveGameDownloadDialogShow()
        DialogHelper.showDialog(
            context,
            R.string.archive_dialog_title.toResString(),
            R.string.archive_download_dialog_content.toResString(),
            R.string.archive_download_dialog_confirm.toResString(),
            com.gh.gamecenter.common.R.string.cancel.toResString(),
            confirmClickCallback = {
                NewFlatLogUtils.logCloudArchiveGameDownloadDialogClick(R.string.archive_download_dialog_confirm.toResString())
                VHelper.disableLaunchGameAfterInstallation()
                EventBus.getDefault().post(EBReuse("download"))
            },
            cancelClickCallback = {
                NewFlatLogUtils.logCloudArchiveGameDownloadDialogClick(com.gh.gamecenter.common.R.string.cancel.toResString())
            },
            extraConfig = DialogHelper.Config(centerTitle = true, centerContent = true)
        )
    }

    private fun applyArchive(
        context: Context,
        entrance: String,
        packageName: String,
        config: String,
        archiveEntity: ArchiveEntity,
        gameEntity: GameEntity?
    ) {
        VArchiveHelper.getArchiveFile(archiveEntity.md5)?.run {

            RetrofitManager.getInstance().newApi
                .postArchiveUsage(archiveEntity.gameId, archiveEntity.id)
                .subscribeOn(Schedulers.io())
                .subscribe()

            VArchiveHelper.applyGameArchive(context, packageName, config, this) { packageName, isSuccess ->
                runOnUiThread {
                    if (isSuccess) {
                        VHelper.launch(context, packageName)
                    } else {
                        ToastUtils.toast(R.string.archive_apply_fail.toResString())
                    }
                }
            }
        }

        NewFlatLogUtils.logCloudArchiveDownloadOrApply(
            archiveEntity.name,
            entrance,
            gameEntity?.id ?: "",
            gameEntity?.name ?: "",
            archiveEntity.id,
            false
        )
    }

    private fun downloadArchive(
        context: Context,
        entrance: String,
        fragment: Fragment,
        packageName: String,
        viewModel: BaseCloudArchiveViewModel,
        archiveEntity: ArchiveEntity,
        downloadBtn: TextView,
        gameEntity: GameEntity?,
        downloadCompletedListener: (() -> Unit)? = null
    ) {
        // 执行下载
        VArchiveHelper.downloadArchive(archiveEntity)

        // 下载进度弹窗
        val archiveLoadingDialog = Dialog(context, com.gh.gamecenter.common.R.style.DialogWindowTransparent)
        val archiveLoadingBinding = DialogArchiveLoadingBinding.inflate(context.layoutInflater)
        showArchiveLoadingDialog(archiveLoadingDialog, archiveLoadingBinding.root)

        // 下载进度监听
        AutoUnregisteredSimpleDownloadListener(archiveEntity.id, fragment, object : DownloadListener {
            override fun onError(error: DownloadError) {
                dismissArchiveLoadingDialog(archiveLoadingDialog)
                ToastUtils.toast(R.string.archive_download_fail.toResString())
            }

            override fun onProgress(progress: Float) {
                archiveLoadingBinding.run {
                    progressTv.text = "${progress.roundTo(1)}%"
                    progressBar.progress = progress.toInt()
                }
            }

            override fun onSizeReceived(fileSize: Long) {
                // Do nothing
            }

            override fun onStatusChanged(status: DownloadStatus) {
                when (status) {
                    DownloadStatus.COMPLETED -> {
                        dismissArchiveLoadingDialog(archiveLoadingDialog)
                        downloadBtn.text = R.string.archive_apply.toResString()
                        viewModel.getArchiveConfigString {
                            showApplyArchiveTipDialog(context, entrance, packageName, it, archiveEntity, gameEntity)
                        }
                        downloadCompletedListener?.invoke()
                    }
                    else -> {
                        // Do nothing
                    }
                }
            }

            override fun onSpeedChanged(speed: Float) {
                // Do nothing
            }

        })

        NewFlatLogUtils.logCloudArchiveDownloadOrApply(
            archiveEntity.name,
            entrance,
            gameEntity?.id ?: "",
            gameEntity?.name ?: "",
            archiveEntity.id,
            true
        )

        SensorsBridge.trackEvent(
            "CloudSaveDownload",
            "cloud_save_name", archiveEntity.name,
            "game_id", gameEntity?.id ?: "",
            "game_name", gameEntity?.name ?: "",
            "source_entrance", entrance
        )
    }

    private fun showArchiveLoadingDialog(
        archiveLoadingDialog: Dialog,
        contentView: View
    ) {
        archiveLoadingDialog.run {
            setCancelable(false)
            setCanceledOnTouchOutside(false)
            requestWindowFeature(Window.FEATURE_NO_TITLE)
            setContentView(contentView)
            show()
        }
        archiveLoadingDialog.window?.attributes?.apply {
            width = DisplayUtils.getScreenWidth() - 120F.dip2px()
            archiveLoadingDialog.window?.attributes = this
        }
    }

    private fun showApplyArchiveTipDialog(
        context: Context,
        entrance: String,
        packageName: String,
        config: String,
        archiveEntity: ArchiveEntity,
        gameEntity: GameEntity?
    ) {
        runOnUiThread {
            DialogHelper.showDialog(
                context,
                R.string.archive_dialog_title.toResString(),
                R.string.archive_apply_dialog_content.toResString(),
                R.string.archive_apply.toResString(),
                com.gh.gamecenter.common.R.string.cancel.toResString(),
                {
                    if(gameEntity.is32() && VHelper.isInnerInstalled(packageName) && !VCore.getInstance().isExtPackageInstalled()) {
                        // 32位的游戏 并且 32位畅玩没有安装 并且 一体化
                        VHelper.newCwValidateVspaceBeforeAction(context, gameEntity) {}
                    } else {
                        applyArchive(context, entrance, packageName, config, archiveEntity, gameEntity)
                        NewFlatLogUtils.logCloudArchiveApplyDialogRelated("cloud_save_overwrite_dialog_click", "使用")
                        SensorsBridge.trackEvent(
                            "CloudSaveOverwriteDialogClick",
                            "game_id", gameEntity?.id ?: "",
                            "game_name", gameEntity?.name ?: "",
                            "button_name", "使用"
                        )
                    }
                },
                {
                    NewFlatLogUtils.logCloudArchiveApplyDialogRelated("cloud_save_overwrite_dialog_click", "取消")
                    SensorsBridge.trackEvent(
                        "CloudSaveOverwriteDialogClick",
                        "game_id", gameEntity?.id ?: "",
                        "game_name", gameEntity?.name ?: "",
                        "button_name", "取消"
                    )
                },
                extraConfig = DialogHelper.Config(centerTitle = true)
            )

            NewFlatLogUtils.logCloudArchiveApplyDialogRelated("cloud_save_overwrite_dialog_show")
            SensorsBridge.trackEvent(
                "CloudSaveOverwriteDialogShow",
                "game_id", gameEntity?.id ?: "",
                "game_name", gameEntity?.name ?: ""
            )
        }
    }

    private fun dismissArchiveLoadingDialog(archiveLoadingDialog: Dialog) {
        if (archiveLoadingDialog.isShowing) {
            archiveLoadingDialog.dismiss()
        }
    }
}