package com.base.browserwhite.ui.activity.bookmark

import androidx.core.view.isVisible
import com.base.browserwhite.bean.HistoryBean
import com.base.browserwhite.databinding.FragmentHistoryBinding
import com.base.browserwhite.ui.fragment.BaseFragment
import com.base.browserwhite.ui.views.BookmarkDialog.showBookmarkMoreDialog
import com.base.browserwhite.utils.KotlinExt.toFormatTime
import com.base.browserwhite.utils.SpBeanUtils
import com.google.gson.Gson

class HistoryFragment : BaseFragment<FragmentHistoryBinding>() {


    private lateinit var historyAdapter: HistoryAdapter
    private val historyList = arrayListOf<HistoryBean>()


    override val binding: FragmentHistoryBinding by lazy {
        FragmentHistoryBinding.inflate(layoutInflater)
    }

    private var viewInit: Boolean = false

    override fun setView() {

        historyAdapter = HistoryAdapter()
        historyAdapter.moreAction = { view, item ->
            requireContext().showBookmarkMoreDialog(
                view, 1,
                deleteAction = {

                },
                editAction = {},
                selectAction = {})
        }
        binding.rv.adapter = historyAdapter

        viewInit = true
        initData()
    }

    fun initData() {
        if (!viewInit) return
        historyList.clear()
        val list = SpBeanUtils.getSpBeanList(SpBeanUtils.HISTORY_SP_KEY)
        val gson = Gson()
        val item = list.map { gson.fromJson(it, HistoryBean::class.java) }

        var time = ""
        item.sortedBy { it.time }.forEach {
            if (time != it.time.toFormatTime()) {
                it.showTime = true
                time = it.time.toFormatTime()
            }
            historyList.add(it)
        }
        binding.llEmpty.isVisible = historyList.isEmpty()
        runCatching {
            historyAdapter.submitList(historyList)
        }
    }

}