package com.base.locationsharewhite.ui.main

import android.Manifest
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.view.LayoutInflater
import androidx.activity.addCallback
import androidx.core.view.updatePadding
import androidx.lifecycle.lifecycleScope
import com.base.locationsharewhite.BuildConfig
import com.base.locationsharewhite.R
import com.base.locationsharewhite.databinding.ActivityMainBinding
import com.base.locationsharewhite.fcm.MsgMgr
import com.base.locationsharewhite.helper.BaseActivity
import com.base.locationsharewhite.helper.MyApplication
import com.base.locationsharewhite.helper.config.ConstConfig
import com.base.locationsharewhite.location.LocationLoginUtils
import com.base.locationsharewhite.map.MapUtils.addLocationMarker
import com.base.locationsharewhite.ui.howuse.HowUseActivity
import com.base.locationsharewhite.ui.locationmap.LocationMapActivity
import com.base.locationsharewhite.ui.set.SettingActivity
import com.base.locationsharewhite.ui.views.DialogView.showAppExitDialog
import com.base.locationsharewhite.utils.BarUtils
import com.base.locationsharewhite.utils.LogEx
import com.base.locationsharewhite.utils.PermissionUtils.checkLocationPermission
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.Marker

class MainActivity : BaseActivity<ActivityMainBinding>(), OnMapReadyCallback {

    private val TAG = "MainActivity"

    override val binding: ActivityMainBinding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }

    private var map: GoogleMap? = null
    private lateinit var mainPresenter: MainPresenter
    private var marker: Marker? = null
    private var actionId: Int? = null

    override fun initView() {
        LogEx.logDebug(TAG, "initView")
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())

        if (isLanguageRecreate(MyApplication.mainLanguage)) {
            return
        }

        mainPresenter = MainPresenter(this)
        actionId = intent.extras?.getInt("actionId")
        LogEx.logDebug(TAG, "initView actionId=$actionId", true)

        if (!checkLocationPermission()) {
            launcher.launch(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)) {

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    launcher.launch(arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION)) {

                    }
                }

            }
        }
        //访问运动数据
        //https://developer.android.com/develop/sensors-and-location/location/transitions?hl=zh-cn
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            launcher.launch(arrayOf(Manifest.permission.ACTIVITY_RECOGNITION)) {

            }
        }

        val mapFragment =
            supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment?
        mapFragment?.getMapAsync(this)

        LocationLoginUtils.login()
    }

    override fun initListener() {
        super.initListener()
        if (isLanguageRecreate(MyApplication.mainLanguage)) {
            return
        }
        onBackPressedDispatcher.addCallback {
            showAppExitDialog()
        }
        binding.llMapLocation.setOnClickListener {
            startActivity(Intent(this, LocationMapActivity::class.java))
        }
        binding.ivFangda.setOnClickListener {
            startActivity(Intent(this, LocationMapActivity::class.java))
        }
        binding.llMap.setOnClickListener {
            startActivity(Intent(this, LocationMapActivity::class.java))
        }
        binding.flMyLocationCode.setOnClickListener {
            startActivity(Intent(this, LocationCodeActivity::class.java))
        }
        binding.flShareMyLocation.setOnClickListener {
            startActivity(Intent(this, LocationShareActivity::class.java))
        }
        binding.flHowUse.setOnClickListener {
            startActivity(Intent(this, HowUseActivity::class.java))
        }
        binding.flSettings.setOnClickListener {
            startActivity(Intent(this, SettingActivity::class.java))
        }
        binding.tvTittle.setOnClickListener {
            if (BuildConfig.DEBUG) {
                MsgMgr.sendNotification(this, ConstConfig.ACTION_SHARE_LOCATION)
            }
        }
    }


    override fun onResume() {
        super.onResume()
        val isRecreate = updateAppLanguage(MyApplication.mainLanguage, TAG) {
            MyApplication.mainLanguage = it
        }
        if (isRecreate) {
            return
        }
        mainPresenter.requestLocationUpdates()
        mainPresenter.startLocationJob(lifecycleScope)

        isRunning = true
    }

    override fun onPause() {
        super.onPause()
        if (isRunning) {
            mainPresenter.cancelLocationUpdates()
            mainPresenter.cancelLocationJob()
        }
    }


    var reSetZoom = true
    override fun onMapReady(googleMap: GoogleMap) {
        map = googleMap

        LogEx.logDebug(TAG, "onMapReady")
        mainPresenter.startLocationJob(lifecycleScope)
        mainPresenter.uiLocationCallback = {
            LogEx.logDebug(TAG, "uiLocationCallback $it")
            changeLocation(it, true, reSetZoom)
            reSetZoom = false
        }
    }

    private fun changeLocation(latLng: LatLng, cameraFollow: Boolean, reSetZoom: Boolean) {
        LogEx.logDebug(TAG, "getLastKnowLocation ${latLng.latitude} ${latLng.longitude}")
        initMyMarker(latLng)

        if (cameraFollow) {
            if (reSetZoom) {
                map?.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15f))
            } else {
                map?.moveCamera(CameraUpdateFactory.newLatLng(latLng))
            }
        }
    }

    /**
     * 初始化marker
     */
    private fun initMyMarker(latLng: LatLng) {
        if (marker == null) {
            val myAvatar = LayoutInflater.from(this).inflate(R.layout.avatar_me, null)
            marker = map?.addLocationMarker(myAvatar, latLng, "my")
        }
    }
}