package com.base.browserwhite.ui.fragment

import android.content.Intent
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo.IME_ACTION_DONE
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnScrollListener
import androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_IDLE
import com.base.browserwhite.R
import com.base.browserwhite.bean.ConstObject.BAIDU
import com.base.browserwhite.bean.ConstObject.BING
import com.base.browserwhite.bean.ConstObject.DUCKDUCKGO
import com.base.browserwhite.bean.ConstObject.GOOGLE
import com.base.browserwhite.bean.ConstObject.YAHOO
import com.base.browserwhite.bean.ConstObject.YANDEX
import com.base.browserwhite.bean.WebSiteBean
import com.base.browserwhite.bean.defaultValue
import com.base.browserwhite.bean.webSiteGroupBeanList
import com.base.browserwhite.databinding.FragmentHomeBinding
import com.base.browserwhite.service.StayNotificationService.Companion.restartStartStayNotification
import com.base.browserwhite.ui.activity.scanqrc.ScanQRCActivity
import com.base.browserwhite.ui.activity.webbrowser.WebBrowserActivity
import com.base.browserwhite.ui.activity.webstore.WevStoreActivity
import com.base.browserwhite.ui.adapter.NewsAdapter
import com.base.browserwhite.ui.adapter.WebsiteAdapter
import com.base.browserwhite.ui.views.DialogViews.showSearchEngineDialog
import com.base.browserwhite.ui.views.itemtouch.MyItemTouchHelperCallBack
import com.base.browserwhite.utils.AppPreferences
import com.base.browserwhite.utils.LogEx
import java.util.concurrent.atomic.AtomicBoolean


class HomeFragment : BaseFragment<FragmentHomeBinding>() {

    private val TAG = "HomeFragment"
    override val binding: FragmentHomeBinding by lazy {
        FragmentHomeBinding.inflate(layoutInflater)
    }

    private lateinit var websiteAdapter: WebsiteAdapter
    private lateinit var itemTouchHelper: ItemTouchHelper
    private lateinit var newsAdapter: NewsAdapter
    private var isLoadingMore: AtomicBoolean = AtomicBoolean(false)

    override fun setView() {

        binding.rvWeb.layoutManager = GridLayoutManager(requireContext(), 4, LinearLayoutManager.VERTICAL, false)
        websiteAdapter = WebsiteAdapter(0) { bean ->
            if (bean.name == "Increase") {
                requireContext().startActivity(Intent(requireContext(), WevStoreActivity::class.java))
            } else {
                requireContext().startActivity(Intent(requireContext(), WebBrowserActivity::class.java).apply {
                    putExtra("uri", bean.url)
                })
            }

        }
        binding.rvWeb.adapter = websiteAdapter
        itemTouchHelper = ItemTouchHelper(MyItemTouchHelperCallBack())
        itemTouchHelper.attachToRecyclerView(binding.rvWeb)

        newsAdapter = NewsAdapter(lifecycleScope)
        binding.rvNews.adapter = newsAdapter
        binding.rvNews.addOnScrollListener(object : OnScrollListener() {
            var i = 0

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
            }

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                i++
                if (newState == SCROLL_STATE_IDLE && !binding.rvNews.canScrollVertically(1)) {
                    loadMoreData()
                }
            }
        })
        loadMoreData()
    }

    private fun loadMoreData() {
        if (isLoadingMore.get()) return
        isLoadingMore.set(true)
        LogEx.logDebug(TAG, "load data")
        newsAdapter.loadMore(
            errorCallBack = {
                isLoadingMore.set(false)
            },
            callBack = {
                LogEx.logDebug(TAG, "loadMore BACK")
                isLoadingMore.set(false)
            })
    }

    override fun onResume() {
        super.onResume()
        setWebSiteData()
    }

    private fun setWebSiteData() {
        val recommendWebSite = webSiteGroupBeanList.flatMap { it.items }.filter { bean ->
            AppPreferences.getInstance().getBoolean("${bean.id}_${bean.name}", defaultValue(bean.name))
        }
        websiteAdapter.setData(recommendWebSite, WebSiteBean(name = "Increase").apply {
            localIcon = R.mipmap.increase
            increase = true
        })
    }

    override fun setListener() {
        super.setListener()
        binding.llWeather.setOnClickListener {
            requireContext().restartStartStayNotification()
        }

        binding.flSearchEngine.setOnClickListener {
//            requireContext().showSearchEngineDialog { website ->
//                when (website) {
//                    GOOGLE -> {
//                        binding.ivSearchEngine.setImageResource(R.mipmap.h_s_google)
//                    }
//
//                    BING -> {
//                        binding.ivSearchEngine.setImageResource(R.mipmap.h_s_bing)
//                    }
//
//                    YAHOO -> {
//                        binding.ivSearchEngine.setImageResource(R.mipmap.h_s_yahoo)
//                    }
//
//                    DUCKDUCKGO -> {
//                        binding.ivSearchEngine.setImageResource(R.mipmap.h_s_xuckd)
//                    }
//
//                    YANDEX -> {
//                        binding.ivSearchEngine.setImageResource(R.mipmap.h_s_yandex)
//                    }
//
//                    BAIDU -> {
//                        binding.ivSearchEngine.setImageResource(R.mipmap.h_s_baidu)
//                    }
//
//                }
//            }
        }

        binding.editWeb.setOnEditorActionListener(object : TextView.OnEditorActionListener {
            override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
                if (actionId == IME_ACTION_DONE) {
                    requireActivity().startActivity(Intent(requireContext(), WebBrowserActivity::class.java).apply {

                        val base = "https://www.google.com/"
                        val content = v?.text
                        val search = "search?q=${content}&oq=${content}"
                        putExtra("uri", "$base$search")
                    })
                    return true; // 返回true表示事件已处理
                }
                return false

            }
        })


        binding.flScan.setOnClickListener {
            requireContext().startActivity(Intent(requireContext(), ScanQRCActivity::class.java))
        }
    }


}