package com.base.browserwhite.ui.activity.webbrowser


import android.graphics.Color
import androidx.activity.addCallback
import androidx.core.view.updatePadding
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import com.base.browserwhite.R
import com.base.browserwhite.databinding.ActivityWebBrowserBinding
import com.base.browserwhite.ui.activity.BaseActivity
import com.base.browserwhite.ui.fragment.WebViewFragment
import com.base.browserwhite.utils.BarUtils


class WebBrowserActivity : BaseActivity<ActivityWebBrowserBinding>() {

    override val binding: ActivityWebBrowserBinding by lazy {
        ActivityWebBrowserBinding.inflate(layoutInflater)
    }
    private val fragmentList = arrayListOf<Fragment>()
    private var currentFragment: WebViewFragment? = null

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

        val uri = intent.extras?.getString("uri") ?: ""
        binding.editWeb.setText(uri)


        addNewWebSite(uri)

    }

    private fun checkLeftRight() {
        if (currentFragment?.canGoBack() == true) {
            binding.ivLeft.setImageResource(R.mipmap.left_s)
        } else {
//            binding.ivLeft.setImageResource(R.mipmap.left_n)
            binding.ivLeft.setImageResource(R.mipmap.left_s)
        }
        if (currentFragment?.canGoForward() == true) {
            binding.ivRight.setImageResource(R.mipmap.right_s)
        } else {
            binding.ivRight.setImageResource(R.mipmap.right_n)
        }
    }

    override fun initListener() {
        super.initListener()

        onBackPressedDispatcher.addCallback {

            if (currentFragment?.canGoBack() == true) {
                currentFragment?.goBack()
            } else {
                finishToMain()
            }
        }
        binding.ivLeft.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        binding.ivRight.setOnClickListener {
            if (currentFragment?.canGoForward() == true) {
                currentFragment?.goForward()
            }
        }
        binding.ivHome.setOnClickListener {
            finishToMain()
        }
    }

    private fun addNewWebSite(uri: String) {
        val myFragment = WebViewFragment(uri)
        val transaction: FragmentTransaction = supportFragmentManager.beginTransaction()
        transaction.replace(R.id.container, myFragment)
        transaction.commit()
        fragmentList.add(myFragment)
        currentFragment = myFragment
        currentFragment?.onPageFinished = { uriString ->
            uriString?.let { binding.editWeb.setText(it) }
            checkLeftRight()
        }
    }

}