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

import android.content.Intent
import android.graphics.Color
import androidx.activity.addCallback
import androidx.core.view.updatePadding
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.ui.adapter.NewsAdapter
import com.base.browserwhite.utils.BarUtils
import com.base.browserwhite.utils.LogEx
import com.base.browserwhite.utils.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 {
            finishToMain()
        }
        binding.ivGuanbi.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
    }

    private fun requestMore(categoryId: Int, changeCategory: Boolean = false) {
        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 (lastNewsId == null || changeCategory) {
                    newsAdapter.submitList(it)
                } else {
                    newsAdapter.addAll(it)
                }
                helper.trailingLoadState = LoadState.NotLoading(false)
            }

        })
    }

}