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

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

/**
 * 编辑书签
 */
class BookmarkEditActivity : BaseActivity<ActivityBookmarkEditBinding>() {

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

    @SuppressLint("SetTextI18n")
    override fun initView() {

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

        binding.editName.setText(editBookmark?.name)
        binding.editUrl.setText(editBookmark?.url)
        binding.ivSelectorNav.isSelected = true
        binding.tvFolder.text = editBookmark?.folder
        binding.tvSave.isEnabled = true

    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            finishToMain()
        }
        binding.flFanhui.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        binding.llFolder.setOnClickListener {
            BookmarkFolderActivity.selectFolder = editBookmark?.folder ?: ""
            launcher.launch(Intent(this, BookmarkFolderActivity::class.java)) {
                val json = it.data?.extras?.getString("Folder", "") ?: ""
                val bean = Gson().fromJson(json, BookmarkBean::class.java)
                editBookmark?.folder = bean.name
                editBookmark?.folderId = bean.id
                binding.tvFolder.text = editBookmark?.folder ?: ""
            }
        }
        binding.editUrl.addTextChangedListener {
            binding.tvSave.isEnabled = !it.isNullOrEmpty()
        }
        binding.editName.addTextChangedListener {
            binding.tvSave.isEnabled = !it.isNullOrEmpty()
        }

        binding.tvSave.setOnClickListener {
            if (editBookmark == null) {
                throw Exception("bug no BookmarkBean")
            }
            editBookmark?.color = ColorUtils.getRandomColor()
            editBookmark?.let { SpBeanUtils.addSpBean(BOOKMARK_SP_KEY, it) }
            finish()
        }
    }

    companion object {
        var editBookmark: BookmarkBean? = null
    }

}