package com.gh.gamecenter.setting.view

import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.text.TextUtils
import android.view.View
import androidx.core.content.FileProvider
import com.alibaba.android.arouter.launcher.ARouter
import com.gh.gamecenter.common.base.fragment.ToolbarFragment
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.utils.setSwitchAnimation
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.core.provider.IBuildConfigProvider
import com.gh.gamecenter.core.provider.IPackageUtilsProvider
import com.gh.gamecenter.core.utils.MtaHelper
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.setting.R
import com.gh.gamecenter.setting.databinding.FragmentGameDownloadSettingBinding
import java.io.File

class GameDownloadSettingFragment : ToolbarFragment() {

    private var mBinding: FragmentGameDownloadSettingBinding? = null

    override fun getLayoutId() = 0

    override fun getInflatedLayout() =
        FragmentGameDownloadSettingBinding.inflate(layoutInflater).apply { mBinding = this }.root

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

    private fun initStatus() {
        var dirPath = ""
        mBinding?.autoInstallItem?.run {
            titleTv.text = getString(R.string.setting_install_auto)
            switchLottie.visibility = View.VISIBLE
            root.setOnClickListener {
                if (switchLottie.isAnimating) return@setOnClickListener
                val status = SPUtils.getBoolean(Constants.SP_AUTO_INSTALL, true)
                MtaHelper.onEvent("我的光环_设置", "设置功能", "下载完成自动安装游戏")
                MtaHelper.onEvent("我的光环_设置", "自动安装游戏", if (status) "关闭" else "打开")
                switchLottie.setSwitchAnimation(status)
                switchLottie.playAnimation()
                SPUtils.setBoolean(Constants.SP_AUTO_INSTALL, !status)
            }
        }
        mBinding?.concernGameItem?.run {
            titleTv.text = getString(R.string.setting_favorite_auto)
            switchLottie.visibility = View.VISIBLE
            root.setOnClickListener {
                if (switchLottie.isAnimating) return@setOnClickListener
                val status = SPUtils.getBoolean(Constants.SP_CONCERN_GAME, true)
                MtaHelper.onEvent("我的光环_设置", "设置功能", "安装完成自动关注游戏")
                MtaHelper.onEvent("我的光环_设置", "自动关注游戏", if (status) "关闭" else "打开")
                switchLottie.setSwitchAnimation(status)
                switchLottie.playAnimation()
                SPUtils.setBoolean(Constants.SP_CONCERN_GAME, !status)
            }
        }
        mBinding?.trafficItem?.run {
            titleTv.text = getString(R.string.setting_traffic_download)
            switchLottie.visibility = View.VISIBLE
            root.setOnClickListener {
                if (switchLottie.isAnimating) return@setOnClickListener
                val status = SPUtils.getBoolean(getTrafficDownloadHintKey(), false)
                switchLottie.setSwitchAnimation(status)
                switchLottie.playAnimation()
                SPUtils.setBoolean(getTrafficDownloadHintKey(), !status)
            }
        }
        mBinding?.downloadPathItem?.run {
            titleTv.text = getString(R.string.setting_download_path)
            contentTv.text = getString(R.string.setting_download_path_des)
            contentTv.visibility = View.VISIBLE
            root.setOnClickListener {
                MtaHelper.onEvent("我的光环_设置", "设置功能", "游戏下载目录")
                if (TextUtils.isEmpty(dirPath)) dirPath = Environment.getExternalStorageDirectory().path + "/gh-files"
                startFilePath(dirPath)
            }
        }
        mBinding?.picPathItem?.run {
            titleTv.text = getString(R.string.setting_pic_path)
            contentTv.text = getString(R.string.setting_pic_path_des)
            contentTv.visibility = View.VISIBLE
            root.setOnClickListener {
                MtaHelper.onEvent("我的光环_设置", "设置功能", "图片保存目录")
                if (TextUtils.isEmpty(dirPath)) dirPath =
                    Environment.getExternalStorageDirectory().path + "/pictures/ghzhushou"
                startFilePath(dirPath)
            }
        }
        mBinding?.cleanPackageItem?.run {
            titleTv.text = getString(R.string.setting_clean_package)
            textMoreTv.visibility = View.VISIBLE
            root.setOnClickListener {
                MtaHelper.onEvent("我的光环_设置", "设置功能", "安装包清理")
                ARouter.getInstance().build(RouteConsts.activity.cleanApkActivity).navigation()
            }
        }
        mBinding?.run {
            autoInstallItem.switchLottie.setSwitchAnimation(SPUtils.getBoolean(Constants.SP_AUTO_INSTALL, true))
            concernGameItem.switchLottie.setSwitchAnimation(SPUtils.getBoolean(Constants.SP_CONCERN_GAME, true))
            trafficItem.switchLottie.setSwitchAnimation(SPUtils.getBoolean(getTrafficDownloadHintKey(), false))
        }
    }

    private fun startFilePath(dirPath: String) {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        try {
            val uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                val buildConfig =
                    ARouter.getInstance().build(RouteConsts.provider.buildConfig).navigation() as? IBuildConfigProvider
                FileProvider.getUriForFile(requireContext(), buildConfig?.getApplicationId() ?: "", File(dirPath))
            } else {
                Uri.fromFile(File(dirPath))
            }
            intent.setDataAndType(uri, "file/*")
            intent.addCategory(Intent.CATEGORY_OPENABLE)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            startActivity(intent)
        } catch (e: Exception) {
            toast("无法找到文件管理器")
            e.printStackTrace()
        }
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        mBinding?.run {
            root.setBackgroundColor(R.color.background.toColor(requireContext()))
            autoInstallItem.switchLottie.setSwitchAnimation(SPUtils.getBoolean(Constants.SP_AUTO_INSTALL, true))
            concernGameItem.switchLottie.setSwitchAnimation(SPUtils.getBoolean(Constants.SP_CONCERN_GAME, true))
            trafficItem.switchLottie.setSwitchAnimation(SPUtils.getBoolean(getTrafficDownloadHintKey(), false))
        }
    }

    companion object {
        @JvmStatic
        fun getTrafficDownloadHintKey(): String {
            val packageUtils =
                ARouter.getInstance().build(RouteConsts.provider.packageUtils).navigation() as? IPackageUtilsProvider
            return packageUtils?.getGhVersionName() + "traffic_download_hint"
        }
    }
}