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

import com.base.browserwhite.bean.HistoryBean
import com.base.browserwhite.databinding.FragmentHistoryBinding
import com.base.browserwhite.ui.fragment.BaseFragment
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()
        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)
        }
        runCatching {
            historyAdapter.submitList(historyList)
        }
    }

}