package com.keyboard.journey

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.recyclerview.widget.LinearLayoutManager
import com.gyf.immersionbar.ktx.immersionBar
import com.keyboard.journey.adapter.BannerImgAdapter
import com.keyboard.journey.adapter.MainDataAdapter
import com.keyboard.journey.bean.CategoryDataBean
import com.keyboard.journey.bean.MainDataBean
import com.keyboard.journey.databinding.JourneyActivityMainBinding
import com.keyboard.journey.util.NetworkCallback
import com.keyboard.journey.util.NetworkUtil
import com.keyboard.journey.util.getRandomInt
import com.keyboard.journey.util.isMyInputMethodDefault
import com.keyboard.journey.util.isMyInputMethodEnabled
import com.keyboard.journey.util.shareAppInfo
import com.youth.banner.listener.OnPageChangeListener
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import org.libpag.PAGFile
import kotlin.coroutines.resume


class JourneyMActivity : AppCompatActivity() {
    private lateinit var binding: JourneyActivityMainBinding
    private var imgList: MutableList<Int> = mutableListOf()
    private var dataList: MutableList<MainDataBean> = mutableListOf()
    private var mainAdapter: MainDataAdapter? = null
    private var backPressedOnce = false
    private var currentBannerType = 0

    private lateinit var bannerStr0: String
    private lateinit var bannerStr1: String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = JourneyActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        bannerStr0 = getString(R.string.recommend)
        bannerStr1 = getString(R.string.cool)
        initBar()
        initView()
        initData()
    }


    private suspend fun getFetchCategory(
        key: String,
        offset: Int,
        pageSize: Int,
    ): CategoryDataBean? {
        return try {
            suspendCancellableCoroutine<CategoryDataBean> { continuation ->
                NetworkUtil().fetchCategory(
                    key,
                    offset,
                    pageSize,
                    object : NetworkCallback<List<CategoryDataBean>> {
                        override fun onSuccess(data: List<CategoryDataBean>) {
                            continuation.resume(data[0])
                        }

                        override fun onFailure(errorMessage: String) {
                        }
                    })
            }
        } catch (e: Exception) {
            return null
        }
    }

    @OptIn(DelicateCoroutinesApi::class)
    private fun initData() {
        loadingPlay()
        NetworkUtil().fetchData(object : NetworkCallback<List<MainDataBean>> {
            @SuppressLint("NotifyDataSetChanged")
            override fun onSuccess(data: List<MainDataBean>) {
                GlobalScope.launch(Dispatchers.IO) {
                    val jobs = data.map { bean ->
                        GlobalScope.async(Dispatchers.IO) {
                            val resultCategory = getFetchCategory(
                                bean.key, getRandomInt(1, 15),
                                getRandomInt(5, 16),
                            )
                            bean.items = resultCategory?.items!!
                            bean
                        }
                    }
                    val list = awaitAll(*jobs.toTypedArray())
                    withContext(Dispatchers.Main) {
                        dataList.clear()
                        dataList.addAll(list)
                        Log.d(JourneyApp.TAG, "--------------dataList=${dataList.size}")
                        mainAdapter?.notifyDataSetChanged()
                        loadingClose()
                    }
                }

            }

            override fun onFailure(errorMessage: String) {
                LogUtil.logMsgD(errorMessage)
            }
        })
    }

    private fun initBar() {
        immersionBar {
            statusBarDarkFont(true)
            statusBarView(binding.view)
        }
    }

    private fun setupDrawerListener() {
        binding.drawer.addDrawerListener(object : DrawerLayout.DrawerListener {
            override fun onDrawerSlide(drawerView: View, slideOffset: Float) {}

            override fun onDrawerOpened(drawerView: View) {
                drawerView.isClickable = true
            }

            override fun onDrawerClosed(drawerView: View) {}

            override fun onDrawerStateChanged(newState: Int) {}
        })
    }

    private fun initClick() {
        binding.menuBtn.setOnClickListener {
            if (binding.drawer.isDrawerOpen(GravityCompat.START)) {
                binding.drawer.closeDrawer(GravityCompat.START)
            } else {
                binding.drawer.openDrawer(GravityCompat.START)
            }
        }
        binding.bannerBtn.setOnClickListener {
            for (data in dataList) {
                Log.d(JourneyApp.TAG, "----------  data=${data.title}")
            }
            val recommend = dataList.filter { it.title.contains("For You") }
            val cool = dataList.filter { it.title.contains(bannerStr1) }
            if (currentBannerType == 0) {
                Log.d(JourneyApp.TAG, "----------0  recommend.size=${recommend.size}")
                val intent = Intent(this, JourneyCategoryDetailsActivity::class.java)
                intent.putExtra(
                    JourneyCategoryDetailsActivity.CATEGORY_DETAILS_BEAN_KEY,
                    recommend[0]
                )
                startActivity(intent)
            } else if (currentBannerType == 1) {
                Log.d(JourneyApp.TAG, "----------1  cool.size=${cool.size}")
                val intent = Intent(this, JourneyCategoryDetailsActivity::class.java)
                intent.putExtra(JourneyCategoryDetailsActivity.CATEGORY_DETAILS_BEAN_KEY, cool[0])
                startActivity(intent)
            }
        }
        binding.applyKeyboardBtn.setOnClickListener {
            val enabled = isMyInputMethodEnabled(this)
            val default = isMyInputMethodDefault(this)
            if (enabled && default) {
                binding.dialogStepLayout.visibility = View.GONE

                Toast.makeText(
                    this,
                    "The keyboard has been set up successfully!",
                    Toast.LENGTH_SHORT
                ).show()
            } else {
                binding.dialogStepLayout.visibility = View.VISIBLE
                updateSetMyInputMethod()
            }
        }
        binding.step1Btn.setOnClickListener {
            val intent = Intent(Settings.ACTION_INPUT_METHOD_SETTINGS)
            startActivity(intent)
        }

        binding.step2Btn.setOnClickListener {
            val imeManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            imeManager.showInputMethodPicker()
        }

        binding.dialogStepLayout.setOnClickListener {
            binding.dialogStepLayout.visibility = View.GONE
        }

        binding.privacyBtn.setOnClickListener {
            val privacyPolicyUrl = "https://sites.google.com/view/privacy-policy-html-app"
            val intent = Intent(Intent.ACTION_VIEW)
            intent.data = Uri.parse(privacyPolicyUrl)
            startActivity(intent)
        }
        binding.shareBtn.setOnClickListener {
            shareAppInfo(this)
        }
    }

    override fun onBackPressed() {
        if (binding.drawer.isDrawerOpen(GravityCompat.START)) {
            binding.drawer.closeDrawer(GravityCompat.START);
        } else {
            if (backPressedOnce) {
                super.onBackPressed()
                return
            }

            backPressedOnce = true
            Toast.makeText(this, "Press again to exit!", Toast.LENGTH_SHORT).show()
            // 两秒钟内再次按返回键取消退出操作
            val handler = android.os.Handler()
            handler.postDelayed({ backPressedOnce = false }, 2000)
        }
    }

    private fun initView() {
        binding.rv.layoutManager = LinearLayoutManager(this)
        mainAdapter = MainDataAdapter(this, dataList)
        binding.rv.adapter = mainAdapter

        imgList.add(R.mipmap.recommend_top_banner_img)
        imgList.add(R.mipmap.cool_top_banner_img)
        val adapter = BannerImgAdapter(imgList)
        binding.banner.setAdapter(adapter).addBannerLifecycleObserver(this) //添加生命周期观察者
        binding.banner.addOnPageChangeListener(object : OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {

            }

            override fun onPageSelected(position: Int) {
                when (position) {
                    0 -> {
                        currentBannerType = 0
                        binding.indicatorLayout.setBackgroundColor(getColor(R.color.banner_indicator_one_bg))
                        binding.indicatorImg.setImageResource(R.mipmap.top_banner_one_img)
                        binding.indicatorTxt.text = bannerStr0
                        binding.indicatorGoBg.setCardBackgroundColor(getColor(R.color.banner_indicator_one_go_bg_color))
                        binding.indicatorLineOneBg.setBackgroundColor(getColor(R.color.banner_indicator_one_go_bg_color))
                        binding.indicatorLineTowBg.setBackgroundColor(getColor(R.color.black_10))
                    }

                    1 -> {
                        currentBannerType = 1
                        binding.indicatorLayout.setBackgroundColor(getColor(R.color.banner_indicator_tow_bg))
                        binding.indicatorImg.setImageResource(R.mipmap.top_banner_tow_img)
                        binding.indicatorTxt.text = bannerStr1
                        binding.indicatorGoBg.setCardBackgroundColor(getColor(R.color.banner_indicator_tow_go_bg_color))
                        binding.indicatorLineOneBg.setBackgroundColor(getColor(R.color.black_10))
                        binding.indicatorLineTowBg.setBackgroundColor(getColor(R.color.banner_indicator_tow_go_bg_color))
                    }
                }
            }

            override fun onPageScrollStateChanged(state: Int) {

            }
        })
        setupDrawerListener()
        initClick()
    }

    private fun loadingPlay() {
        binding.loadingLayout.visibility = View.VISIBLE
        binding.indicatorGoBg.visibility = View.GONE
        val pagFile = PAGFile.Load(assets, "loading.pag")
        binding.pagView.composition = pagFile
        binding.pagView.setRepeatCount(0)
        binding.pagView.play()
    }

    private fun loadingClose() {
        binding.loadingLayout.visibility = View.GONE
        binding.indicatorGoBg.visibility = View.VISIBLE
        if (binding.pagView.isPlaying) {
            binding.pagView.stop()
        }
    }

    private fun updateSetMyInputMethod() {
        val enabled = isMyInputMethodEnabled(this)
        val default = isMyInputMethodDefault(this)
        if (enabled) {
            binding.step1Btn.background = getDrawable(R.drawable.drw_gray_select_bg)
            binding.step1Btn.text = "Step 1:Enabled"
            binding.step1Btn.setTextColor(Color.parseColor("#999999"))
        } else {
            binding.step1Btn.background = getDrawable(R.mipmap.activate_btn_bg)
            binding.step1Btn.text = "Step 1:Select"
            binding.step1Btn.setTextColor(Color.parseColor("#000000"))
        }
        if (default) {
            binding.step2Btn.background = getDrawable(R.drawable.drw_gray_select_bg)
            binding.step2Btn.text = "Step 2:Enabled"
            binding.step1Btn.setTextColor(Color.parseColor("#999999"))
        } else {
            binding.step2Btn.background = getDrawable(R.mipmap.activate_btn_bg)
            binding.step2Btn.text = "Step 2:Select"
            binding.step1Btn.setTextColor(Color.parseColor("#000000"))
        }
    }

}