package com.waytous.anticollision.ui.video

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.text.SpannableString
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.content.res.AppCompatResources
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.graphics.scale
import androidx.core.view.get
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.MediaItem
import com.mapbox.geojson.FeatureCollection
import com.mapbox.geojson.Point
import com.mapbox.maps.CameraOptions
import com.mapbox.maps.MapView
import com.mapbox.maps.MapboxMap
import com.mapbox.maps.Style
import com.mapbox.maps.ViewAnnotationOptions
import com.mapbox.maps.extension.style.expressions.dsl.generated.interpolate
import com.mapbox.maps.extension.style.image.image
import com.mapbox.maps.extension.style.layers.generated.symbolLayer
import com.mapbox.maps.extension.style.layers.properties.generated.IconAnchor
import com.mapbox.maps.extension.style.sources.generated.geoJsonSource
import com.mapbox.maps.extension.style.sources.generated.rasterDemSource
import com.mapbox.maps.extension.style.style
import com.mapbox.maps.extension.style.terrain.generated.terrain
import com.mapbox.maps.plugin.LocationPuck2D
import com.mapbox.maps.plugin.Plugin
import com.mapbox.maps.plugin.annotation.annotations
import com.mapbox.maps.plugin.annotation.generated.PointAnnotation
import com.mapbox.maps.plugin.annotation.generated.PointAnnotationManager
import com.mapbox.maps.plugin.annotation.generated.PointAnnotationOptions
import com.mapbox.maps.plugin.annotation.generated.createPointAnnotationManager
import com.mapbox.maps.plugin.gestures.gestures
import com.mapbox.maps.plugin.locationcomponent.OnIndicatorBearingChangedListener
import com.mapbox.maps.plugin.locationcomponent.OnIndicatorPositionChangedListener
import com.mapbox.maps.plugin.locationcomponent.location
import com.mapbox.maps.plugin.logo.logo
import com.mapbox.maps.viewannotation.ViewAnnotationManager
import com.waytous.anticollision.R
import com.waytous.anticollision.databinding.FragmentVideoHomeBinding
import com.waytous.anticollision.ui.view.MoreFeaturesPopup
import com.waytous.anticollision.ui.view.WorkStatusEditPopup
import com.waytous.anticollision.utils.getBitmapFromVectorDrawable
import com.waytous.anticollision.utils.setTextSize
import java.io.File

class VideoHomeFragment : Fragment() {

    private lateinit var binding: FragmentVideoHomeBinding

    private lateinit var mapView: MapView

    private lateinit var mapboxMap: MapboxMap

    private lateinit var viewAnnotationManager: ViewAnnotationManager

    private lateinit var pointAnnotationManager: PointAnnotationManager

    private lateinit var pointAnnotation: PointAnnotation

    private var player1: ExoPlayer? = null

    private var player2: ExoPlayer? = null

    private lateinit var workStatusEditPopup: WorkStatusEditPopup

    private lateinit var moreFeaturesPopup: MoreFeaturesPopup

    companion object {
        fun newInstance() = VideoHomeFragment()

        const val MY_VEHICLE_NORMAL = "my_vehicle_normal"

        private const val GEOJSON_SOURCE_ID = "tile"
        private const val LATITUDE = 108.926593
        private const val LONGITUDE = 34.213389
        private const val ZOOM = 14.0
    }

    private val viewModel: VideoHomeViewModel by viewModels()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentVideoHomeBinding.inflate(inflater, container, false)
        context ?: return binding.root
        workStatusEditPopup = WorkStatusEditPopup(context).also {
            it.setOutSideDismiss(true)
            it.popupGravity = Gravity.TOP or Gravity.CENTER
            it.setBackgroundColor(R.color.color_99000000)
        }
        moreFeaturesPopup = MoreFeaturesPopup(context).also {pupop->
            pupop.setOutSideDismiss(true)
            pupop.popupGravity = Gravity.TOP or Gravity.CENTER
            pupop.maskOffsetY = 20
            pupop.setBackgroundColor(R.color.color_99000000)
            pupop.contentView.findViewById<AppCompatTextView>(R.id.moreFeatureCollect).setOnClickListener {
                findNavController().navigate(R.id.action_navigation_video_Home_to_collectFragment)
                pupop.dismiss()
            }
        }
        val templateString = getString(R.string.current_speed, 36)
        val spannableString = SpannableString(templateString)
        binding.workStatusEdit.setOnClickListener {
            workStatusEditPopup.showPopupWindow(binding.currentWorkStatusLayout)
        }
        binding.speedText.setTextSize(spannableString, templateString)
        mapView = binding.root.findViewById<MapView?>(R.id.mapView).also {
            it.logo.enabled = false
        }
        mapboxMap = mapView.getMapboxMap()
        viewAnnotationManager = mapView.viewAnnotationManager
        initLocationComponent()
        initPlayer()
        binding.toggleMore.setOnClickListener {
            moreFeaturesPopup.showPopupWindow(it)
        }
        return binding.root
    }

    private fun initLocationComponent() {
        val locationComponentPlugin = mapView.location

        mapView.getMapboxMap().loadStyle(
            style(styleUri = Style.MAPBOX_STREETS) {
                +geoJsonSource(GEOJSON_SOURCE_ID) {
                    url("asset://xian.geojson")
                }
            }
        ) {
            val bitmap: Bitmap? =
                activity?.getBitmapFromVectorDrawable(R.drawable.my_vehicle_normal, 4)
            val annotationPlugin = mapView.annotations
            val pointAnnotationOptions: PointAnnotationOptions = PointAnnotationOptions()
                .withPoint(
                    Point.fromLngLat(
                        LATITUDE,
                        LONGITUDE
                    )
                )
                .withIconImage(bitmap!!.apply {
                    scale(bitmap.width / 4, bitmap.height / 4)
                })
                .withIconAnchor(IconAnchor.BOTTOM)
                .withDraggable(false)
            pointAnnotationManager = annotationPlugin.createPointAnnotationManager()
            pointAnnotation = pointAnnotationManager.create(pointAnnotationOptions)
        }
        mapView.getMapboxMap().setCamera(
            CameraOptions.Builder().center(
                Point.fromLngLat(
                    LATITUDE,
                    LONGITUDE
                )
            ).zoom(ZOOM).build()
        )
//        locationComponentPlugin.locationPuck = LocationPuck2D(
//            bearingImage = VectorDrawableCompat.create(
//                resources,
//                R.drawable.my_vehicle_normal,
//                null
//            ), scaleExpression = interpolate {
//                linear()
//                zoom()
//                stop {
//                    literal(0.0)
//                    literal(0.6)
//                }
//                stop {
//                    literal(20.0)
//                    literal(1.0)
//                }
//            }.toJson()
//        )
    }

    private fun setMyCarLocation(vehicleResId: Int) {
        val bitmap = BitmapFactory.decodeResource(resources, vehicleResId)
        val markerWidth = bitmap.width
        val markerHeight = bitmap.height
    }

    private fun prepareStyle(styleUri: String, imageId: String, bitmap: Bitmap) = style(styleUri) {
        +image(MY_VEHICLE_NORMAL) {
            bitmap(bitmap)
        }
    }

    private fun initPlayer() {
        val uri1 = Uri.fromFile(File(activity!!.filesDir, "飞书20230420-181456.mp4"))
        player1 = activity?.let {
            ExoPlayer.Builder(it).build().apply {
                setMediaItem(MediaItem.Builder().setUri(uri1).build())
            }
        }
        binding.videoView1.player = player1
        player1?.prepare()
        val uri2 = Uri.fromFile(File(activity!!.filesDir, "飞书20230420-181512.mp4"))
        player2 = activity?.let {
            ExoPlayer.Builder(it).build().apply {
                setMediaItem(MediaItem.Builder().setUri(uri2).build())
            }
        }
        binding.videoView2.player = player2
        player2?.prepare()
        player1?.play()
        player2?.play()
    }

    override fun onDestroyView() {
        player1?.release()
        player2?.release()
        super.onDestroyView()
    }
}