package com.gh.gamecenter.common.dialog

import android.annotation.SuppressLint
import android.content.ActivityNotFoundException
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.launcher.ARouter
import com.gh.gamecenter.common.R
import com.gh.gamecenter.common.base.fragment.BaseDialogFragment
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.databinding.DialogNotificationHintBinding
import com.gh.gamecenter.common.entity.NotificationStyleEntity
import com.gh.gamecenter.common.entity.NotificationUgc
import com.gh.gamecenter.common.utils.PermissionHelper
import com.gh.gamecenter.common.utils.fromHtml
import com.gh.gamecenter.core.provider.IBuildConfigProvider
import com.gh.gamecenter.core.utils.GsonUtils
import com.lightgame.utils.Utils
import org.json.JSONArray
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import kotlin.random.Random

// 通知权限弹窗
class NotificationHintDialogFragment : BaseDialogFragment() {

    private var mNotificationUgc: NotificationUgc? = null
    private val mBinding: DialogNotificationHintBinding by lazy { DialogNotificationHintBinding.inflate(layoutInflater) }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return mBinding.root
    }

    @Suppress("DEPRECATION")
    @SuppressLint("SetTextI18n")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val jsonString = getJsonFromAssets()
        if (jsonString.isNullOrEmpty()) {
            Utils.log("Failed to obtain configuration file")
            return
        }
        val index = Random.nextInt(2)
        val jsonArray = JSONArray(jsonString)
        val jsonObj = jsonArray.getJSONObject(index)
        if (!jsonObj.has(mNotificationUgc?.value)) {
            Utils.log("ugc type error")
            return
        }
        val styleEntityJson = jsonObj.getJSONObject(mNotificationUgc!!.value)
        val styleEntity = GsonUtils.fromJson(styleEntityJson.toString(), NotificationStyleEntity::class.java)
        val drawableId = resources.getIdentifier(styleEntity.image, "drawable", requireContext().packageName)
        mBinding.run {
            notificationIv.setImageDrawable(ContextCompat.getDrawable(requireContext(), drawableId))
            notificationTitle.text = styleEntity.title
            notificationContent.text = styleEntity.content.fromHtml()
            if (index == 0) {
                closeIv.setImageDrawable(
                    ContextCompat.getDrawable(
                        requireContext(),
                        R.drawable.ic_notification_close_1
                    )
                )
            } else {
                activateTv.background =
                    ContextCompat.getDrawable(requireContext(), R.drawable.bg_notification_open_btn_style_1)
                activateTv.text = "优雅的开启"
            }

            activateTv.setOnClickListener {
                dismissAllowingStateLoss()
                val buildConfig =
                    ARouter.getInstance().build(RouteConsts.provider.buildConfig).navigation() as? IBuildConfigProvider
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    //这种方案适用于 API 26, 即8.0（含8.0）以上可以用
                    val intent = Intent()
                    intent.action = Settings.ACTION_APP_NOTIFICATION_SETTINGS
                    intent.putExtra(Settings.EXTRA_APP_PACKAGE, buildConfig?.getApplicationId())
                    try {
                        startActivity(intent)
                    } catch (e: ActivityNotFoundException) {
                        PermissionHelper.toPermissionSetting(requireActivity())
                    }
                } else {
                    PermissionHelper.toPermissionSetting(requireActivity())
                }
            }

            closeIv.setOnClickListener {
                dismissAllowingStateLoss()
            }
        }

        dialog?.setCanceledOnTouchOutside(true)
    }

    private fun getJsonFromAssets(): String {
        val stringBuilder = StringBuilder()
        var bufferedReader: BufferedReader? = null
        var inputStreamReader: InputStreamReader? = null
        try {
            inputStreamReader = InputStreamReader(requireContext().assets.open("notification_style.json"))
            bufferedReader = BufferedReader(inputStreamReader)
            var line: String?
            while (bufferedReader.readLine().also { line = it } != null) {
                stringBuilder.append(line)
            }
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            inputStreamReader?.close()
            bufferedReader?.close()
        }
        return stringBuilder.toString()
    }

    companion object {
        @JvmStatic
        fun getInstance(ugc: NotificationUgc) = NotificationHintDialogFragment().apply {
            mNotificationUgc = ugc
        }
    }
}
