package es.verdnatura.presentation.view.commom

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.print.PrintAttributes
import android.print.PrintManager
import android.view.GestureDetector
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ImageView
import androidx.activity.OnBackPressedCallback
import androidx.activity.OnBackPressedDispatcher
import androidx.core.view.GestureDetectorCompat
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentWebBinding
import es.verdnatura.presentation.common.OnBackPressedListener
import es.verdnatura.presentation.common.OnOptionsSelectedListener
import es.verdnatura.presentation.common.ToolBarAdapterTooltip
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.feature.main.activity.MainActivity
import org.json.JSONObject
import kotlin.math.abs

@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class WebFragment(
    var entryPoint: String = ""
) : Fragment(), OnBackPressedListener {
    private lateinit var gestureDetector: GestureDetectorCompat
    fun getLayoutId(): Int = R.layout.fragment_web
    private lateinit var customDialog: CustomDialog
    private lateinit var backDispatcher: OnBackPressedDispatcher
    private lateinit var binding: FragmentWebBinding

    companion object {
        fun newInstance(entryPoint: String) = WebFragment(entryPoint)
    }

    fun init() {
        customDialog = CustomDialog(requireContext())
        setToolbar()
        setWeb()

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_web, container, false)
        binding.lifecycleOwner = this
        return binding.root

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        super.onViewCreated(view, savedInstanceState)

        requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner,
            object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    if (!onBackPressedHandled()) {
                        isEnabled = false
                        requireActivity().onBackPressedDispatcher
                    }
                }
            })

        gestureDetector = GestureDetectorCompat(requireActivity(),
            object : GestureDetector.SimpleOnGestureListener() {
                override fun onFling(
                    e1: MotionEvent?, e2: MotionEvent, velocityX: Float, velocityY: Float
                ): Boolean {
                    val deltaX = (e2.x - e1?.x!!)
                    val deltaY = (e2.y - e1.y)
                    val deltaAbsX = abs(deltaX)
                    val deltaAbsY = abs(deltaY)
                    if (deltaAbsX > deltaAbsY) {
                        if (velocityX > 2000 && velocityY < 500 && velocityY >= 0) {

                            binding.webView.goBack()
                            return true

                        }

                    }
                    return false
                }
            })
        init()
        super.onViewCreated(view, savedInstanceState)
    }

    @SuppressLint("ClickableViewAccessibility", "SetJavaScriptEnabled")
    private fun setWeb() {

        binding.webView.webChromeClient = WebChromeClient(

        )

        val webSettings = binding.webView.settings
        webSettings.javaScriptEnabled = true
        webSettings.domStorageEnabled = true
        webSettings.loadWithOverviewMode = true
        webSettings.useWideViewPort = true
        webSettings.builtInZoomControls = true
        webSettings.displayZoomControls = false
        webSettings.setSupportZoom(true)
        webSettings.allowFileAccess = true

        binding.webView.setOnTouchListener { v, event ->
            gestureDetector.onTouchEvent(event)
        }
        binding.webView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(
                view: WebView?, request: WebResourceRequest?
            ): Boolean {
                binding.webView.loadUrl(request?.url.toString())
                return true
            }
        }

        val dataScanned = JSONObject(entryPoint)

        if (dataScanned.toString().contains("cmr?")) {
            val pdfUrl = "${dataScanned.get("web")}"
            val googleDocsViewerUrl = "https://docs.google.com/gview?embedded=true&url=$pdfUrl"
            binding.webView.loadUrl(googleDocsViewerUrl)
        } else {
            binding.webView.loadUrl(dataScanned.get("web").toString())
        }

    }

    private fun setToolbar() {

        binding.mainToolbar.toolbarTitle.text = buildString {
            append(getString(R.string.item))
            append(JSONObject(entryPoint).get("entryPoint").toString())
        }

        val listIcons: ArrayList<ImageView> = ArrayList()
        val iconPrint = ImageView(context)
        iconPrint.setImageResource(R.drawable.ic_print_black_24dp)
        iconPrint.tooltipText = getString(R.string.print)

        //listIcons.add(iconPrint)

        binding.mainToolbar.toolbarIcons.adapter =
            ToolBarAdapterTooltip(listIcons, object : OnOptionsSelectedListener {
                override fun onOptionsItemSelected(item: Drawable) {

                    when (item) {
                        iconPrint.drawable -> createWebPrintJob(binding.webView)
                    }

                }
            })
        binding.mainToolbar.toolbarIcons.layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)

    }

    private fun createWebPrintJob(webView: WebView) {

        // Get a PrintManager instance
        (activity?.getSystemService(Context.PRINT_SERVICE) as? PrintManager)?.let { printManager ->

            val jobName = "${getString(R.string.app_name)} Document"

            // Get a print adapter instance
            val printAdapter = webView.createPrintDocumentAdapter(jobName)

            // Create a print job with name and adapter instance
            printManager.print(
                jobName, printAdapter, PrintAttributes.Builder().build()
            ).also { printJob ->
                println("job printed")
                // Save the job object for later status checking
                // printJobs += printJob
            }
        }
    }

    override fun onBackPressedHandled(): Boolean {

        if (binding.webView.canGoBack()) {
            binding.webView.goBack()
        } else {
            (context as MainActivity).onMyBackPressed()
        }

        return true
    }

}

