package com.base.browserwhite.ui.activity.news

import android.content.Intent
import android.graphics.Color
import android.view.View
import androidx.activity.addCallback
import androidx.core.view.updatePadding
import com.base.browserwhite.ads.AdmobMaxHelper
import com.base.browserwhite.ads.AdmobMaxHelper.lastShowInter
import com.base.browserwhite.ads.admob.AdmobNativeUtils
import com.base.browserwhite.bean.NewsCategory
import com.base.browserwhite.databinding.ActivityNewsBinding
import com.base.browserwhite.databinding.ItemTabNewsBinding
import com.base.browserwhite.ui.activity.BaseActivity
import com.base.browserwhite.utils.BarUtils
import com.base.browserwhite.utils.LogEx
import com.base.browserwhite.help.NewsUtils
import com.chad.library.adapter4.QuickAdapterHelper
import com.chad.library.adapter4.loadState.LoadState
import com.chad.library.adapter4.loadState.trailing.TrailingLoadStateAdapter

class NewsActivity : BaseActivity<ActivityNewsBinding>() {

    private val TAG = "NewsActivity"
    override val binding: ActivityNewsBinding by lazy {
        ActivityNewsBinding.inflate(layoutInflater)
    }
    private lateinit var newsAdapter: NewsAdapter
    private lateinit var helper: QuickAdapterHelper
    private var isLoading = false
    private var currentCategory: Int = 0

    override fun initView() {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())

        newsAdapter = NewsAdapter(false, clickAction = {
            startActivity(Intent(this, NewsDetailActivity::class.java).apply {
                putExtra("url", it)
            })
        })
        helper =
            QuickAdapterHelper.Builder(newsAdapter).setTrailingLoadStateAdapter(object : TrailingLoadStateAdapter.OnTrailingListener {
                override fun onLoad() {
                    LogEx.logDebug(TAG, "onLoad")
                    requestMore(currentCategory)
                }

                override fun onFailRetry() {
                    LogEx.logDebug(TAG, "onFailRetry")
                    requestMore(currentCategory)
                }

                override fun isAllowLoading(): Boolean {
                    LogEx.logDebug(TAG, "isLoading=$isLoading")
                    return !isLoading
                }
            }).build()
        binding.rv.adapter = helper.adapter

        val category = arrayOf(
            NewsCategory(0, "Latest"),
            NewsCategory(101, "Political"),
            NewsCategory(301, "Sports"),
            NewsCategory(501, "Entertainment"),
            NewsCategory(2401, "Word"),
            NewsCategory(2001, "Lifestyle"),
            NewsCategory(1802, "Public Safety"),
            NewsCategory(401, "Economic"),
        )
        category.forEach { bean ->
            val tabBinding = ItemTabNewsBinding.inflate(layoutInflater)
            tabBinding.tv.text = bean.name
            binding.tabLayout.addView(tabBinding.root)
        }

        binding.tabLayout.observeIndexChange { fromIndex, toIndex, reselect, fromUser ->
            if (!reselect) {
                val bean = category[toIndex]
                currentCategory = bean.id
                requestMore(bean.id, true)
            }
        }

    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            if (System.currentTimeMillis() - lastShowInter > 10 * 1000 * 1000 || lastShowInter == 0L) {
                AdmobMaxHelper.admobMaxShowInterstitialAd(this@NewsActivity, false) {
                    if (it) {
                        lastShowInter = System.currentTimeMillis()
                    }
                    finishToMain()
                }
            } else {
                finishToMain()
            }
        }
        binding.ivGuanbi.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
    }

    private fun requestMore(categoryId: Int, changeCategory: Boolean = false) {
        if (changeCategory) {
            newsAdapter.submitList(listOf())
            binding.ivPlaceHolder.visibility = View.VISIBLE
        }
        isLoading = true
        helper.trailingLoadState = LoadState.None
        val lastNewsId = newsAdapter.getLastPageNumber()
        LogEx.logDebug(TAG, "requestMore lastNewsId=$lastNewsId")
        NewsUtils.requestNews(categoryId = categoryId, pageNumber = lastNewsId, errorCallBack = {
            isLoading = false
            LogEx.logDebug(TAG, "errorCallBack")
        }, beanCallBack = {
            isLoading = false
            binding.root.post {
                LogEx.logDebug(TAG, "beanCallBack")
                if (it.isNotEmpty()) {
                    binding.ivPlaceHolder.visibility = View.GONE
                }
                val newsAdList = AdmobNativeUtils.addNativeAdNewsBean(it)
                if (lastNewsId == null || changeCategory) {
                    newsAdapter.submitList(newsAdList)
                } else {
                    newsAdapter.addAll(newsAdList)
                }
                helper.trailingLoadState = LoadState.NotLoading(false)
            }

        })
    }

}