Почему сейчас, когда я открываю ссылку с доменом как у MAXI_RETAIL_HOST, то он открывается через браузер, хотя не должен? package ru.maxi.mobile.feature.webview.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.View
import android.webkit.DownloadListener
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import by.kirich1409.viewbindingdelegate.viewBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import ru.maxi.mobile.BuildConfig
import ru.maxi.mobile.R
import ru.maxi.mobile.base.ui.MvvmBaseFragment
import ru.maxi.mobile.common.utils.android.screenArgs
import ru.maxi.mobile.common.utils.android.setupDarkMode
import ru.maxi.mobile.core.data.LoadableData
import ru.maxi.mobile.databinding.FragmentWebviewBinding
import java.net.URL
import ru.maxi.mobile.core.network.BuildConfig as NetworkBuildConfig

/**
 * Фрагмент для отображения WebView
 */
@AndroidEntryPoint
class WebViewFragment : MvvmBaseFragment(R.layout.fragment_webview) {

    private val screenArgs by screenArgs(WebViewArgs)

    private val viewBinding by viewBinding(FragmentWebviewBinding::bind)

    private val viewModel by viewModels<WebViewViewModel>()

    override val analyticsName: String = "_WebView"

    @SuppressLint("SetJavaScriptEnabled")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        actionBarManager.setTitle(screenArgs.title)
        actionBarManager.showBackButton()

        with(viewBinding) {
            webView.apply {
                settings.apply {
                    textZoom = 100
                    javaScriptEnabled = true
                }
                webViewClient = CustomWebViewClient()
                setupDarkMode()
                setDownloadListener(CustomDownloadListener())
            }
            noConnectionView.setOnActionButtonClickListener { webView.reload() }
        }

        with(viewLifecycleOwner) {
            lifecycleScope.launch {
                repeatOnLifecycle(Lifecycle.State.STARTED) {
                    launch { viewModel.viewState.collect(::onViewStateChange) }
                }
            }
        }
    }

    private fun onViewStateChange(viewState: LoadableData<URL>) {
        when (viewState) {
            is LoadableData.Loading -> with(viewBinding) {
                loaderView.show()
                noConnectionView.isVisible = false
                webView.isInvisible = true
                viewState.value?.let(::loadPage)
            }

            is LoadableData.Error -> with(viewBinding) {
                loaderView.hide()
                noConnectionView.isVisible = true
                webView.isInvisible = true
            }

            is LoadableData.Success -> with(viewBinding) {
                loaderView.hide()
                noConnectionView.isVisible = false
                webView.isVisible = true
                loadPage(viewState.value)
            }
        }
    }

    private fun loadPage(url: URL) {
        if (viewBinding.webView.url != url.toString()) {
            viewBinding.webView.loadUrl(url.toString())
        }
    }

    private inner class CustomDownloadListener : DownloadListener {
        override fun onDownloadStart(
            url: String?,
            userAgent: String?,
            contentDisposition: String?,
            mimeType: String?,
            contentLength: Long,
        ) {
            Log.d("TESTING", "onDoswnloadStart")
            if (url != null) {
                Log.d("TESTING", "onDoswnloadStart mimeType = $mimeType")
                try {
                    val intent = Intent(Intent.ACTION_VIEW)
                    intent.setDataAndType(Uri.parse(url), mimeType)
                    val packageManager = requireContext().packageManager
                    if (intent.resolveActivity(packageManager) != null) {
                        startActivity(intent)
                    } else {
                        val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                        startActivity(browserIntent)
                    }
                } catch (ignored: Exception) {
                }
            }
        }
    }

    private inner class CustomWebViewClient : WebViewClient() {

        override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
            val uri = request.url
            Log.d("TESTING", "uri.host = ${uri.host}")
            return when {
                uri.host != BuildConfig.MAXI_RETAIL_HOST -> {
                    val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(uri.toString()))
                    startActivity(browserIntent)
                    true
                }
                !uri.toString().startsWith(NetworkBuildConfig.REST_API_URL) -> {
                    val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(uri.toString()))
                    startActivity(browserIntent)
                    true
                }

                else -> {
                    super.shouldOverrideUrlLoading(view, request)
                }
            }
        }

        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            super.onPageStarted(view, url, favicon)
            viewModel.onPageStarted()
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
            viewModel.onPageFinished()
        }

        override fun onReceivedError(
            view: WebView?,
            request: WebResourceRequest,
            error: WebResourceError?,
        ) {
            if (request.isForMainFrame) {
                viewModel.onError()
            }
        }

        override fun onReceivedHttpError(
            view: WebView?,
            request: WebResourceRequest,
            errorResponse: WebResourceResponse?,
        ) {
            if (request.isForMainFrame) {
                viewModel.onError()
            }
        }
    }
}