package kr.co.vividnext.sodalive.settings.terms

import android.annotation.SuppressLint
import android.os.Bundle
import android.widget.Toast
import androidx.webkit.WebSettingsCompat
import androidx.webkit.WebViewFeature
import kr.co.vividnext.sodalive.base.BaseActivity
import kr.co.vividnext.sodalive.common.Constants
import kr.co.vividnext.sodalive.common.LoadingDialog
import kr.co.vividnext.sodalive.databinding.ActivityTermsBinding
import org.koin.android.ext.android.inject

class TermsActivity : BaseActivity<ActivityTermsBinding>(ActivityTermsBinding::inflate) {

    private val viewModel: TermsViewModel by inject()

    private lateinit var loadingDialog: LoadingDialog

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        bindData()

        val terms = intent.getStringExtra(Constants.EXTRA_TERMS) ?: Constants.EXTRA_TERMS
        if (terms == Constants.EXTRA_PRIVACY) {
            viewModel.getPrivacyPolicy()
        } else {
            viewModel.getTermsOfService()
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    override fun setupView() {
        if (WebViewFeature.isFeatureSupported(WebViewFeature.FORCE_DARK)) {
            WebSettingsCompat.setForceDark(
                binding.webView.settings,
                WebSettingsCompat.FORCE_DARK_ON
            )
        }

        loadingDialog = LoadingDialog(this, layoutInflater)
        binding.toolbar.tvBack.setOnClickListener { finish() }

        binding.webView.settings.apply {
            javaScriptEnabled = false // 자바스크립트 실행 허용
            javaScriptCanOpenWindowsAutomatically = false // 자바스크립트에서 새창 실 행 허용
            setSupportMultipleWindows(false) // 새 창 실행 허용
            loadWithOverviewMode = true // 메타 태그 허용

            useWideViewPort = true // 화면 사이즈 맞추기 허용
            setSupportZoom(false) // 화면 줌 허용
            builtInZoomControls = false // 화면 확대 축소 허용 여부
        }
    }

    private fun bindData() {
        viewModel.isLoading.observe(this) {
            if (it) {
                loadingDialog.show(screenWidth, "공지사항을 불러오고 있습니다.")
            } else {
                loadingDialog.dismiss()
            }
        }

        viewModel.toastLiveData.observe(this) {
            it?.let { Toast.makeText(applicationContext, it, Toast.LENGTH_LONG).show() }
        }

        viewModel.titleLiveData.observe(this) {
            binding.toolbar.tvBack.text = it
        }

        viewModel.termsLiveData.observe(this) {
            val viewPort =
                "<meta name=\"viewport\" content=\"width=device-width, initial-scale=0.8\">"
            val data = viewPort + it
            binding.webView.loadData(
                data,
                "text/html; charset=utf-8",
                "utf-8"
            )
        }
    }
}
