package com.base.locationsharewhite.ui.main

import android.app.Dialog
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
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.ads.AdsMgr
import com.base.locationsharewhite.ads.AdsShowCallBack
import com.base.locationsharewhite.databinding.ActivityMainBinding
import com.base.locationsharewhite.fcm.NotificationUiUtil.sendAllAllowedNotification
import com.base.locationsharewhite.helper.BaseActivity
import com.base.locationsharewhite.helper.EventUtils
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.service.StayJobService.Companion.startJob
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.ui.views.NotificationDialog.showNotificationTurnOn
import com.base.locationsharewhite.utils.BarUtils
import com.base.locationsharewhite.utils.LogEx
import com.base.locationsharewhite.utils.PermissionUtils.areNotificationsEnabled
import com.base.locationsharewhite.utils.PermissionUtils.checkAllLocationPermission
import com.base.locationsharewhite.utils.PermissionUtils.requestLocationAllowAllTime
import com.base.locationsharewhite.utils.ToastUtils.toast
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
import java.util.concurrent.atomic.AtomicBoolean

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

    private var allowAllTimeDialog: Dialog? = null

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

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

    override fun initView() {

        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())


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

    }

    private var bannerShowed = AtomicBoolean(false)
    override fun onResumeOneShoot() {
        super.onResumeOneShoot()
        val recreated = changeLanguage(this, intent.extras ?: Bundle())
        if (recreated) return

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

        if (!bannerShowed.get()) {
            bannerShowed.set(true)
            AdsMgr.showBanner(binding.flAd) {
                if (!checkAllLocationPermission()) {
                    showAllowAllTimeDialog()
                } else {
                    requestServiceLocationUpdates()
                    if (!areNotificationsEnabled()) {
                        showNotificationTurnOn(launcher)
                    }
                }
            }
        }

        LocationLoginUtils.login()

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

        mainPresenter?.startLocationJob(lifecycleScope)

        val flag = areNotificationsEnabled()
        EventUtils.event("areNotificationsEnabled_$flag", "areNotificationsEnabled=$flag")
    }

    override fun onResume() {
        super.onResume()

        if (checkAllLocationPermission() || allowAllTimeDialog == null) {
            if (!bannerShowed.get()) {
                bannerShowed.set(true)
                AdsMgr.showBanner(binding.flAd)
            }
        }
    }

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


    private fun showAllowAllTimeDialog() {

        if (allowAllTimeDialog == null) {
            allowAllTimeDialog = showLocationAllowAllTimeDialog(
                setAction = {
                    sendAllAllowedNotification(this)
                    requestLocationAllowAllTime(launcher, jumpOutAction = {
                        LogEx.logDebug(TAG, "jumpOutAction")
                    }, permissionAllowCallBack = {
                        if (BuildConfig.DEBUG) {
                            toast("startJob")
                        }
                        this.startJob()
                    })
                },
                dismissAction = {
                    allowAllTimeDialog = null
                })
        }
    }

    override fun initListener() {
        super.initListener()

        onBackPressedDispatcher.addCallback {
            showAppExitDialog()
        }
        binding.llMapLocation.setOnClickListener {
            showAdJump {
                startActivity(Intent(this, LocationMapActivity::class.java))
            }
        }
        binding.ivFangda.setOnClickListener {
            showAdJump {
                startActivity(Intent(this, LocationMapActivity::class.java))
            }
        }
        binding.llMap.setOnClickListener {
            showAdJump {
                startActivity(Intent(this, LocationMapActivity::class.java))
            }
        }
        binding.flMyLocationCode.setOnClickListener {
            showAdJump {
                startActivity(Intent(this, LocationCodeActivity::class.java))
            }
        }
        binding.flShareMyLocation.setOnClickListener {
            showAdJump {
                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 fun showAdJump(jumpAction: () -> Unit) {
        AdsMgr.showInsert(this, false, object : AdsShowCallBack() {
            override fun close(where: Int) {
                LogEx.logDebug(TAG, "close where=$where")
                jumpAction.invoke()
            }

            override fun failed(where: Int) {
                LogEx.logDebug(TAG, "failed where=$where")
                jumpAction.invoke()
            }

            override fun googleFailed(where: Int) {
                LogEx.logDebug(TAG, "googleFailed where=$where")
                jumpAction.invoke()
            }
        })
    }

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