package com.base.superfilemanager.view

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.text.format.Formatter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.blankj.utilcode.util.AppUtils
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.base.superfilemanager.R
import com.base.superfilemanager.activity.PermissionManagerActivity
import com.base.superfilemanager.bean.AppBean
import com.base.superfilemanager.bean.AppBean.Companion.appBeanGson
import com.base.superfilemanager.databinding.DialogAppDetailBinding
import com.base.superfilemanager.helps.ActivityLauncher
import java.text.SimpleDateFormat


object AppDetailDialog {
    private val TAG = "AppDetailDialog"

    @SuppressLint("SimpleDateFormat")
    fun Activity.showAppDetailDialog(
        appBean: AppBean,
        launcher: ActivityLauncher,
        unInstallAction: ((unInstalled: Boolean) -> Unit)? = null
    ) {
        val dialog = BottomSheetDialog(this)
        val binding = DialogAppDetailBinding.inflate(LayoutInflater.from(this))
        dialog.setContentView(binding.root)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()



        binding.tvAppName.text = appBean.appName
        binding.tvPkg.text = appBean.pkg
        binding.ivIcon.setImageDrawable(appBean.icIcon)

        binding.tvVersion.text = AppUtils.getAppVersionName(appBean.pkg)

        val size = Formatter.formatFileSize(this, appBean.appSize)
        binding.tvSize.text = size

        val dateFormat = SimpleDateFormat("MM-dd")
        val installTime = dateFormat.format(appBean.installTime)
        binding.tvInstall.text = installTime

        //应用来源逻辑
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                val installSourceInfo = packageManager.getInstallSourceInfo(appBean.pkg)
//                binding.tvInstaller.text = installSourceInfo.installingPackageName
                if ("com.android.vending" == installSourceInfo.installingPackageName) {
                    binding.tvInstaller.text = getString(R.string.google_play)
                } else {
                    binding.llInstaller.visibility = View.GONE
                }
            } else {
                binding.llInstaller.visibility = View.GONE
            }
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }


        //修改dialog的尺寸
        val lp = dialog.window?.attributes
        lp?.width = ViewGroup.LayoutParams.MATCH_PARENT
        lp?.height = ViewGroup.LayoutParams.WRAP_CONTENT
        dialog.window?.attributes = lp
        dialog.window?.setBackgroundDrawableResource(android.R.color.transparent)

        binding.tvDetail.setOnClickListener {
            val intent = Intent()
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
            intent.setData(Uri.parse("package:" + appBean.pkg))
            startActivity(intent)
            dialog.dismiss()
        }
        binding.tvShare.setOnClickListener {
            dialog.dismiss()
            val uri = "https://play.google.com/store/apps/details?id=${appBean.pkg}&referrer=share"

            //浏览器
            val intentView = Intent(Intent.ACTION_VIEW)
            intentView.setData(Uri.parse(uri))
            // 检查是否有可以处理Intent的应用
            if (intentView.resolveActivity(packageManager) != null) {
                // 启动Intent，打开浏览器
                startActivity(intentView)
            } else {
                //分享文本
                val intent = Intent()
                intent.setAction(Intent.ACTION_SEND)
                intent.putExtra(Intent.EXTRA_TEXT, uri)
                intent.setType("text/plain")
                startActivity(intent)
            }
        }

        binding.tvPermissionCheck.setOnClickListener {
            dialog.dismiss()
            val newIntent = Intent(this, PermissionManagerActivity::class.java)

            val json = appBeanGson.toJson(appBean)
            newIntent.putExtra("AppBean", json)
            startActivity(newIntent)
        }
        binding.tvUninstall.setOnClickListener {
            dialog.dismiss()

            val intent = Intent(Intent.ACTION_DELETE, Uri.parse("package:${appBean.pkg}"))
            launcher.launch(intent) {
                unInstallAction?.invoke(!isInstalled(this, appBean.pkg))
            }
        }

    }

    private fun isInstalled(context: Context, pkg: String, error: (() -> Unit)? = null): Boolean {
        return try {
            context.packageManager.getPackageInfo(pkg, 0)
            true
        } catch (e: Exception) {
            error?.invoke()
            false
        }
    }


}