package com.base.locationsharewhite.ui.main

import android.Manifest
import android.app.Dialog
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.NotificationUiUtil.sendAllAllowedNotification
import com.base.locationsharewhite.helper.BaseActivity
import com.base.locationsharewhite.location.LocationLoginUtils
import com.base.locationsharewhite.map.MapUtils.addLocationMarker
import com.base.locationsharewhite.service.StayJobService.Companion.requestServiceLocationUpdates
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.ui.views.LocationPermissionDialog.showLocationAllowAllTimeDialog
import com.base.locationsharewhite.utils.BarUtils
import com.base.locationsharewhite.utils.LogEx
import com.base.locationsharewhite.utils.PermissionUtils.checkBackgroundLocationPermission
import com.base.locationsharewhite.utils.PermissionUtils.checkBackgroundLocationPermissionDeniedByUser
import com.base.locationsharewhite.utils.PermissionUtils.checkLocationPermission
import com.base.locationsharewhite.utils.PermissionUtils.checkLocationPermissionDeniedByUser
import com.base.locationsharewhite.utils.PermissionUtils.requestLocationAllowAllTime
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

/**
 * https://developer.android.com/about/versions/14/changes/data-safety?hl=zh-cn
 */
class MainActivity : BaseActivity<ActivityMainBinding>(), OnMapReadyCallback {

    private val TAG = "MainActivity"
    private var allowAllTimeDialog: Dialog? = null

    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())

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

        val flag1 = checkLocationPermission()
        val flag2 = checkBackgroundLocationPermission()

        LogEx.logDebug(TAG, "权限自定义弹窗 flag1=$flag1 flag2=$flag2")

        val denyFlag1 = checkLocationPermissionDeniedByUser()
        val denyFlag2 = checkBackgroundLocationPermissionDeniedByUser()
        LogEx.logDebug(TAG, "用户拒绝 denyFlag1=$denyFlag1 denyFlag2=$denyFlag2")

        //访问运动数据
        //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 onResumeOneShoot() {
        super.onResumeOneShoot()
        showNotificationDialog()

        mainPresenter.startLocationJob(lifecycleScope)
        showAllowAllTimeDialog()

//        changeLanguage(this)
    }

    private fun showNotificationDialog() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            launcher.launch(arrayOf(Manifest.permission.POST_NOTIFICATIONS)) {

            }
        }
    }

    override fun onStop() {
        super.onStop()
        mainPresenter.cancelLocationJob()
    }

    private fun showAllowAllTimeDialog() {
        if (!checkLocationPermission() || !checkBackgroundLocationPermission()) {
//            toast("显示权限始终允许弹窗")
            if (allowAllTimeDialog == null) {
                allowAllTimeDialog =
                    showLocationAllowAllTimeDialog(
                        setAction = {
                            sendAllAllowedNotification(this)
                            requestLocationAllowAllTime(launcher, jumpOutAction = {
                                LogEx.logDebug(TAG, "jumpOutAction")
                            }, permissionAllowAction = {})
                        },
                        dismissAction = {
                            allowAllTimeDialog = null
                        })
            }
        } else {
//            toast("不显示权限始终允许弹窗")
            allowAllTimeDialog?.dismiss()
            allowAllTimeDialog = null

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                launcher.launch(arrayOf(Manifest.permission.POST_NOTIFICATIONS)) {}
            }
            requestServiceLocationUpdates()
        }
    }

    override fun initListener() {
        super.initListener()

        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) {

            }
        }
    }

    private 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")
        }
    }
}