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

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

class BookmarkFolderActivity : BaseActivity<ActivityBookmarkFolderBinding>() {

    private lateinit var adapter: BookmarkFolderAdapter

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

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

        binding.ivRootSelector.isSelected = selectFolder == "Root Directory"
        adapter = BookmarkFolderAdapter(selectFolder) { bean ->
            setResult(0, Intent().putExtra("Folder", Gson().toJson(bean)))
            finish()
        }
        binding.rv.adapter = adapter
    }

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

        binding.ivNewFolder.setOnClickListener {
            startActivity(Intent(this, BookmarkFolderEditActivity::class.java))
        }
    }

    private fun initData() {
        val spList = SpBeanUtils.getSpBeanList(BOOKMARK_SP_KEY)
        val folderList = spList.map {
            Gson().fromJson(it, BookmarkBean::class.java)
        }.filter { it.isFolder }
        adapter.submitList(folderList)
    }

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


    companion object {

        var selectFolder: String = "Root Directory"
    }

}