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

import android.graphics.Color
import androidx.activity.addCallback
import androidx.core.view.updatePadding
import com.base.browserwhite.bean.BookmarkBean
import com.base.browserwhite.databinding.ActivityBookMarkBinding
import com.base.browserwhite.ui.activity.BaseActivity
import com.base.browserwhite.utils.BarUtils
import com.base.browserwhite.utils.KotlinExt.toFormatTime
import com.base.browserwhite.utils.SpBeanUtils
import com.base.browserwhite.utils.SpBeanUtils.BOOKMARK_SP_KEY
import com.google.gson.Gson

class BookMarkActivity : BaseActivity<ActivityBookMarkBinding>() {

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

    private lateinit var adapter: BookmarkAdapter

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

        adapter = BookmarkAdapter()

        initData()
    }

    private fun initData() {
        initBookmarkData()
    }

    private fun initBookmarkData() {
        val list = SpBeanUtils.getSpBeanList(BOOKMARK_SP_KEY)
        val items = list.map { Gson().fromJson(it, BookmarkBean::class.java) }
        var time = ""
        items.sortedBy { it.time }.forEach {
            if (time != it.time.toFormatTime()) {
                it.showTime = true
            } else {
                time = it.time.toFormatTime()
            }
        }
        adapter.submitList(items)
    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            finishToMain()
        }
        binding.flFanhui.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }

        binding.tvTabBookmark.setOnClickListener {
            if (binding.tvTabBookmark.isSelected) {
                return@setOnClickListener
            }
            binding.tvTabBookmark.isSelected = true
            binding.tvTabHistory.isSelected = false
        }
        binding.tvTabBookmark.callOnClick()

        binding.tvTabHistory.setOnClickListener {
            if (binding.tvTabHistory.isSelected) {
                return@setOnClickListener
            }
            binding.tvTabHistory.isSelected = true
            binding.tvTabBookmark.isSelected = false
        }


    }


}