package com.jld.vod.view

import android.app.AlertDialog
import android.os.Bundle
import android.os.Handler
import android.os.Message
import com.google.gson.Gson
import com.jld.vod.R
import com.jld.vod.model.bean.LatLongBean
import com.jld.vod.model.event.MapsEvent
import com.jld.vod.utils.LogUtils
import com.jld.vod.utils.SharedPrefUtils
import com.jld.vod.view.widget.GroupMarker
import kotlinx.android.synthetic.main.activity_maps.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONException
import org.mapsforge.core.model.LatLong
import org.mapsforge.map.android.graphics.AndroidGraphicFactory
import org.mapsforge.map.android.util.AndroidUtil
import org.mapsforge.map.android.util.MapViewerTemplate
import org.mapsforge.map.rendertheme.InternalRenderTheme
import org.mapsforge.map.rendertheme.XmlRenderTheme

/**
 * @author ZhaoFuXin
 * @Email：18276061387@163.com
 * @description:
 * @date :2020/6/29 14:59
 */
class MapsActivity : MapViewerTemplate() {

    private var groupMarker: GroupMarker? = null
    private var gson:Gson?= null
    private val mHandler = Handler(Handler.Callback { message ->
            when (message.what) {
                1 -> {
                    val result: String = message.obj.toString()
                    try {
                        val latlng = gson!!.fromJson(result, LatLongBean::class.java)
                        if (latlng != null && latlng.flag) {
                            LogUtils.logD("地图数据：$latlng")
                            //获取本地经纬度
                            val Latitude = latlng.data.Latitude
                            val Longitude = latlng.data.Longitude
                            LogUtils.logD("resultaaaaa$result=="+Longitude+"Latitude"+Latitude)
                            //判断不超出经纬度范围
                            if (Longitude <= 180 && Longitude >= -180 && Latitude <= 90 && Latitude >= -90) {
                                val mylocation = LatLong(Latitude, Longitude)
                                //每次调用清除一次点
                                if (groupMarker != null) {
                                    mapView.layerManager.layers.remove(groupMarker)
                                }
                                //标记点
                                addGroupMarker(mylocation)
                                //移动到所在位置
                                mapView.model.mapViewPosition.center = mylocation
                            }
                        }else{
                            //GPS异常
                            val mylocation = LatLong(0.0, 0.0)
                            //每次调用清除一次点
                            if (groupMarker != null) {
                                mapView.layerManager.layers.remove(groupMarker)
                            }
                            //标记点
                            addGroupMarker(mylocation)
                            //移动到所在位置
                            mapView.model.mapViewPosition.center = mylocation
                        }
                    } catch (e: JSONException) {
                        e.printStackTrace()
                    }
                }
            }
            false
        })
    /**
     * 获取地图viewid
     */
    override fun getMapViewId(): Int {
        return R.id.mapView
    }

    /**
     * 创建碎片缓存
     */
    override fun createTileCaches() {
        tileCaches.add(
            AndroidUtil.createTileCache(
                this, persistableId,
                mapView.model.displayModel.tileSize, this.screenRatio,
                mapView.model.frameBufferModel.overdrawFactor)
        )
    }

    /**
     * 创建层
     */
    override fun createLayers() {
        val tileRendererLayer = AndroidUtil.createTileRendererLayer(
            tileCaches[0],
            mapView.model.mapViewPosition,
            mapFile,
            renderTheme,
            false,
            true,
            false
        )
        mapView.layerManager.layers.add(tileRendererLayer)

        tileRendererLayer.setXmlRenderTheme(renderTheme)
    }

    /**
     * 地图主题
     */
    override fun getRenderTheme(): XmlRenderTheme {
        return InternalRenderTheme.DEFAULT
    }

    /**
     * 初始化
     */
    override fun onStart() {
        super.onStart()
        //接收U盘广播值
        EventBus.getDefault().register(this)

        mapView.model.mapViewPosition.zoomLevel = 15.toByte()

        iv_maps_back.setOnClickListener {
            this.onBackPressed()
        }
        //放大
        iv_maps_add.setOnClickListener{
            mapView.model.mapViewPosition.zoomLevel++
        }
        //缩小
        iv_maps_minus.setOnClickListener{
            mapView.model.mapViewPosition.zoomLevel--
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //初始化gson
        gson = Gson()
    }


    /**
     * 创建mapview
     */
    override fun createMapViews() {
        super.createMapViews()
        mapView.isClickable = true
        mapView.mapScaleBar.isVisible = false
        mapView.setBuiltInZoomControls(false)
        mapView.mapZoomControls.zoomLevelMin = 5.toByte()
        mapView.mapZoomControls.zoomLevelMax = 18.toByte()
    }

    /**
     * 获取本地地图
     */
    override fun getMapFileName(): String? {
        //本地如果没有地图则下载地图
        val region = SharedPrefUtils.getString(this,"region")
        return "/$region.map"
    }

    /**
     * 获取layout
     */
    override fun getLayoutId(): Int {
        return R.layout.activity_maps
    }


    /**
     * 接收服务端的数据
     * @param result
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun getMapsStatusData(result: MapsEvent) {
        //Debuger.logI(TAG,result);
        //异步回调数据
        val msg = Message()
        msg.what = 1
        msg.obj = result.data
        mHandler.sendMessage(msg)
    }

    /**
     *
     */
    private fun addGroupMarker(latLong: LatLong) {
        val bitmap =
            AndroidGraphicFactory.convertToBitmap(resources.getDrawable(R.mipmap.marker_wtk))
        groupMarker = GroupMarker(
            latLong, bitmap, 0, -bitmap.height / 2
            , mapView.layerManager.layers, null
        )
        mapView.addLayer(groupMarker)
    }
    override fun onDestroy() {
        super.onDestroy()
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }
}