package com.waytous.anticollision.ui.home

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.LogUtils
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.extension.observable.eventdata.MapLoadingErrorEventData
import com.mapbox.maps.extension.style.sources.generated.geoJsonSource
import com.mapbox.maps.extension.style.style
import com.mapbox.maps.plugin.Plugin
import com.mapbox.maps.plugin.annotation.annotations
import com.mapbox.maps.plugin.annotation.generated.CircleAnnotationOptions
import com.mapbox.maps.plugin.annotation.generated.createCircleAnnotationManager
import com.mapbox.maps.plugin.delegates.listeners.OnMapLoadErrorListener
import com.mapbox.maps.plugin.logo.LogoPlugin
import com.waytous.anticollision.databinding.FragmentHomeBinding

class HomeFragment : Fragment() {

    private var _binding: FragmentHomeBinding? = null

    private val binding get() = _binding!!

    private lateinit var mapBox:MapboxMap

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val homeViewModel =
            ViewModelProvider(this)[HomeViewModel::class.java]

        _binding = FragmentHomeBinding.inflate(inflater, container, false)
        val root: View = binding.root
        val mapView: MapView = binding.mapView
        val logoPlugin = mapView.getPlugin<LogoPlugin>(Plugin.MAPBOX_LOGO_PLUGIN_ID)
        logoPlugin?.enabled = false
        mapBox = mapView.getMapboxMap().also {
            logoPlugin?.enabled = false
        }
        mapBox.setCamera(
            CameraOptions.Builder()
                .center(
                Point.fromLngLat(
                    LATITUDE,
                    LONGITUDE
                ))
                .zoom(ZOOM).build()
        )
        mapView.getMapboxMap().addOnMapLoadErrorListener(object :OnMapLoadErrorListener{
            override fun onMapLoadError(eventData: MapLoadingErrorEventData) {
                LogUtils.e("OnMapLoadErrorListener:${eventData.message}")
            }

        })
        mapView.addRendererSetupErrorListener {
                error -> LogUtils.e("RendererSetupErrorListener:${error}")
        }

        return root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    companion object {
        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
    }
}