package com.waytous.anticollision.ui.video

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
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.widget.AppCompatTextView
import androidx.core.graphics.scale
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.navigation.fragment.findNavController
import com.blankj.utilcode.util.LogUtils
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.MediaItem
import com.mapbox.geojson.Point
import com.mapbox.maps.CameraOptions
import com.mapbox.maps.MapView
import com.mapbox.maps.MapboxMap
import com.mapbox.maps.extension.style.expressions.dsl.generated.get
import com.mapbox.maps.extension.style.image.image
import com.mapbox.maps.extension.style.layers.generated.fillLayer
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.layers.properties.generated.TextAnchor
import com.mapbox.maps.extension.style.layers.properties.generated.TextRotationAlignment
import com.mapbox.maps.extension.style.layers.properties.generated.Visibility
import com.mapbox.maps.extension.style.sources.generated.geoJsonSource
import com.mapbox.maps.extension.style.style
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.attribution.attribution
import com.mapbox.maps.plugin.compass.compass
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.api.ApiService
import com.waytous.anticollision.databinding.FragmentVideoHomeBinding
import com.waytous.anticollision.ui.MainViewModel
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 kotlinx.coroutines.launch
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 DUMP_AREA_SOURCE = "dumpareasource"
        private const val DUMP_AREA_LAYER = "dumparealayer"
        private const val DUMP_AREA_TEXT_LAYER = "dumpareatextlayer"
        private const val RUNNABLE_AREA_SOURCE = "runableareasource"
        private const val RUNNABLE_AREA_LAYER = "runablearealayer"
        private const val LATITUDE = 119.7622539014
        private const val LONGITUDE = 49.3795031825
//        private const val LATITUDE = 108.926593
//        private const val LONGITUDE = 34.213389
        private const val ZOOM = 16.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
            it.compass.enabled = false
            it.attribution.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
        lifecycleScope.launch {
            val mapData = ApiService.create().dumpAreaVersion("-1")
            viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.CREATED){
                mapView.getMapboxMap().loadStyle(
                    style(styleUri = MainViewModel.MY_MAP_BOX_STYLE) {
                        +geoJsonSource(DUMP_AREA_SOURCE) {
                            data(mapData?.geojson!!)
                            LogUtils.d(get("name").literalValue)
                        }
                        +fillLayer(DUMP_AREA_LAYER,DUMP_AREA_SOURCE){
                            fillColor("#886e26")
                            fillOpacity(0.85)
                            fillAntialias(false)
                            visibility(Visibility.VISIBLE)
                        }
                        +symbolLayer(DUMP_AREA_TEXT_LAYER, DUMP_AREA_SOURCE){
                            textColor(Color.BLACK)
                            textField(get("name"))
                            textFont(listOf("DIN Offc Pro Italic", "Arial Unicode MS Regular"))
                            textLineHeight(1.0)
                            textPadding(1.0)
                            textOffset(listOf(0.5,2.0))
                            textRotationAlignment(TextRotationAlignment.MAP)
                            textAnchor(TextAnchor.TOP)
                            textSize(16.0)
                            textMaxAngle(10.0)
                            visibility(Visibility.VISIBLE)
                        }
                    }
                ) {
                    val bitmap: Bitmap? =
                        activity?.getBitmapFromVectorDrawable(R.drawable.my_vehicle_normal, 4)
                    val annotationPlugin = mapView.annotations
                    val pointAnnotationOptions: PointAnnotationOptions = PointAnnotationOptions()
                        .withPoint(
                            Point.fromLngLat(
                                LONGITUDE,
                                LATITUDE
                            )
                        )
                        .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(requireActivity().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(requireActivity().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()
    }
}