Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
32 kB
2
Indexable
Never
package com.msgp.ui.fragment.distributorFragments

import android.Manifest
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.PendingIntent
import android.app.TaskStackBuilder
import android.content.*
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.location.LocationRequest
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Looper
import android.provider.Settings
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.activity.viewModels
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import com.google.android.gms.tasks.CancellationTokenSource
import com.google.gson.Gson
import com.msgp.R
import com.msgp.cdp.CDPTag
import com.msgp.data.network.model.*
import com.msgp.databinding.ActivitySelectPartyBinding
import com.msgp.databinding.ItemDistributorListBinding
import com.msgp.fcm.CONSTANTS
import com.msgp.ui.activity.HomeActivity
import com.msgp.ui.adapter.distributorAdapter.DistributorFilterableAdapter
import com.msgp.ui.base.BaseActivity
import com.msgp.ui.bottomsheet.SortBySelectPartyBottomSheet
import com.msgp.ui.dialog.GeoLocationUpdateDialog
import com.msgp.ui.viewmodel.LoginViewModel
import com.msgp.utils.customview.alertdialog.SweetAlertDialog
import com.msgp.utils.customview.toast.ToastyType
import com.msgp.utils.extension.*
import com.msgp.utils.fail
import com.msgp.utils.loading
import com.msgp.utils.success
import dagger.hilt.android.AndroidEntryPoint
import java.util.*
import kotlin.collections.ArrayList


@AndroidEntryPoint
class SelectPartyActivity : BaseActivity<LoginViewModel>(),
    DistributorFilterableAdapter.RecordFound {
    var count = 0
    override val vm: LoginViewModel
        get() = viewModel

    private val binding by viewBinding(ActivitySelectPartyBinding::inflate)
    private val viewModel: LoginViewModel by viewModels()
    private val distributorLoginResult: DistributorLoginResult? by lazy { viewModel.getSavedDistributorLoginResult() }
    private lateinit var searchAdapter: DistributorFilterableAdapter
    private lateinit var currentLocation: Location
    private lateinit var deviceSignIn: DeviceSignIn

    var distributorList: ArrayList<DeviceSignIn> = ArrayList()
    var distributorListDefault: ArrayList<DeviceSignIn> = ArrayList()
    private lateinit var itemView: ItemDistributorListBinding
    private lateinit var locationManager: LocationManager


    companion object {
        const val KEY_COMING_FROM = "comingFrom"
        const val KEY_COMING_FROM_HOME_FRAG = "comingFromHomeFrag"
        const val KEY_COMING_FROM_WELCOME = "comingFromWelcome"
        const val KEY_LOCATION_REQUEST = 12527
    }

    private lateinit var fusedLocationClient: FusedLocationProviderClient
    private lateinit var cancellationTokenSource: CancellationTokenSource
    private var sortByPreference: String = ""

    @SuppressLint("MissingPermission")
    @RequiresApi(Build.VERSION_CODES.N)
    @OptIn(ExperimentalStdlibApi::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        val intent: Intent = intent
        val comeFrom: String? = intent.getStringExtra(KEY_COMING_FROM)

        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
        locationManager = getSystemService(LOCATION_SERVICE) as LocationManager


        if (isGPSEnabled()) {
            cancellationTokenSource = CancellationTokenSource()
            fusedLocationClient.requestLocationUpdates(
                com.google.android.gms.location.LocationRequest(), { it ->
                    CONSTANTS.commonDialog(
                        this, "Location ",
                        it.provider.toString()
                    )
                },
                Looper.getMainLooper()
            )
            getUpdatedLocation()
        }

        binding.rvItems.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        searchAdapter = DistributorFilterableAdapter(
            this@SelectPartyActivity,
            this,
            onPartySelected = onPartySelected
        )
        binding.rvItems.adapter = searchAdapter

        binding.txtSearch.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(s: CharSequence?, p1: Int, p2: Int, p3: Int) {
                val string: String = s.toString().lowercase(Locale.getDefault())
                searchAdapter.filter.filter(string)
                viewModel.cdpLogger.logEvent(
                    "MSGPA App Search",
                    string,
                    CDPTag.Action.EVENT_ACTION_CLICK
                )
            }

            override fun afterTextChanged(p0: Editable?) {
            }


        })
        if (comeFrom != null) {
            if (comeFrom == KEY_COMING_FROM_HOME_FRAG) {
                deviceSignInList(distributorLoginResult?.mspin.toString())
            } else {
                distributorList = distributorLoginResult?.deviceSignIn ?: arrayListOf()
                distributorListDefault = distributorLoginResult?.deviceSignIn ?: arrayListOf()
                searchAdapter.updateData(distributorList)
                binding.btnSortBy.visibility = View.GONE

            }
        }

        binding.btnSortBy.setOnClickListener {
            val sortByBottomSheet = SortBySelectPartyBottomSheet(
                preference = sortByPreference,
                sortBy = {
                    sortByPreference = it
                    /* "Last Visited",
                    "MTD Sales (High to Low)",
                    "MTD Sales (Low to High)",
                    "MGP Potential (High to Low)",
                    "MGP Potential (Low to High)*/

                    viewModel.cdpLogger.logEvent(
                        "MSGPA App Select Party - Sort By",
                        it,
                        CDPTag.Action.EVENT_ACTION_CLICK
                    )

                    when (it) {
                        "MGP Potential (Low to High)" -> {
                            val emptyLocation: ArrayList<DeviceSignIn> = ArrayList()
                            val onlyWithLocation: ArrayList<DeviceSignIn> = ArrayList()
                            for (item in distributorList) {
                                if (item.LATITUDE.isNullOrEmpty()) {
                                    emptyLocation.add(item)
                                } else {
                                    onlyWithLocation.add(item)
                                }
                            }
                            onlyWithLocation.sortByDescending { it.MGP_POTENTIALS?.toFloatOrNull() }
                            onlyWithLocation.reverse()
                            val mergedArray = emptyLocation + onlyWithLocation
                            searchAdapter.updateData(mergedArray as java.util.ArrayList<DeviceSignIn>)
                            binding.rvItems.smoothScrollToPosition(0)
                        }
                        "MGP Potential (High to Low)" -> {
                            val emptyLocation: ArrayList<DeviceSignIn> = ArrayList()
                            val onlyWithLocation: ArrayList<DeviceSignIn> = ArrayList()
                            for (item in distributorList) {
                                if (item.LATITUDE.isNullOrEmpty()) {
                                    emptyLocation.add(item)
                                } else {
                                    onlyWithLocation.add(item)
                                }
                            }
                            onlyWithLocation.sortByDescending { it.MGP_POTENTIALS?.toFloatOrNull() }
                            val mergedArray = emptyLocation + onlyWithLocation
                            searchAdapter.updateData(mergedArray as java.util.ArrayList<DeviceSignIn>)
                            binding.rvItems.smoothScrollToPosition(0)
                        }
                        "Sales Achievement (Low to High)" -> {
                            val emptyLocation: ArrayList<DeviceSignIn> = ArrayList()
                            val onlyWithLocation: ArrayList<DeviceSignIn> = ArrayList()
                            for (item in distributorList) {
                                if (item.LATITUDE.isNullOrEmpty()) {
                                    emptyLocation.add(item)
                                } else {
                                    onlyWithLocation.add(item)
                                }
                            }
                            onlyWithLocation.sortByDescending { it.SALES_TREND?.toFloatOrNull() }
                            onlyWithLocation.reverse()
                            val mergedArray = emptyLocation + onlyWithLocation
                            searchAdapter.updateData(mergedArray as java.util.ArrayList<DeviceSignIn>)
                            binding.rvItems.smoothScrollToPosition(0)

                        }
                        "Sales Achievement (High to Low)" -> {
                            val emptyLocation: ArrayList<DeviceSignIn> = ArrayList()
                            val onlyWithLocation: ArrayList<DeviceSignIn> = ArrayList()
                            for (item in distributorList) {
                                if (item.LATITUDE.isNullOrEmpty()) {
                                    emptyLocation.add(item)
                                } else {
                                    onlyWithLocation.add(item)
                                }
                            }
                            onlyWithLocation.sortByDescending { it.SALES_TREND?.toFloatOrNull() }
                            val mergedArray = emptyLocation + onlyWithLocation
                            searchAdapter.updateData(mergedArray as java.util.ArrayList<DeviceSignIn>)
                            binding.rvItems.smoothScrollToPosition(0)

                        }
                        "Last Visited" -> {
                            val emptyLocation: ArrayList<DeviceSignIn> = ArrayList()
                            val onlyWithLocation: ArrayList<DeviceSignIn> = ArrayList()
                            for (item in distributorList) {
                                if (item.LATITUDE.isNullOrEmpty()) {
                                    emptyLocation.add(item)
                                } else {
                                    onlyWithLocation.add(item)
                                }
                            }
                            onlyWithLocation.sortByDescending { it.DUMMY_DATE }
                            onlyWithLocation.reverse()
                            val mergedArray = emptyLocation + onlyWithLocation
                            searchAdapter.updateData(mergedArray as java.util.ArrayList<DeviceSignIn>)
                            binding.rvItems.smoothScrollToPosition(0)
                        }
                    }
                })
            sortByBottomSheet.show(supportFragmentManager, sortByBottomSheet.tag)

        }
    }

    private fun deviceSignInList(mspin: String) {
        val deviceSingInReq = DeviceSignInRequest(mspin)
        viewModel.deviceSignInList(deviceSingInReq).observe(this) { result ->
            result.loading {
                binding.lottieProgress.apply {
                    playAnimation()
                    visible()
                }
            }.success {
                if (it != null) {
                    distributorList = it.result.deviceSignInList
                    distributorListDefault = it.result.deviceSignInList
                    binding.btnSortBy.visibility = View.GONE
                    searchAdapter.updateData(it.result.deviceSignInList)
                }

                binding.lottieProgress.apply {
                    pauseAnimation()
                    invisible()
                }

            }.fail { errorMessage, _ ->
                showToast(0, "$errorMessage", ToastyType.NEGATIVE)
                binding.lottieProgress.apply {
                    pauseAnimation()
                    invisible()
                }
            }
        }
    }

    private val onPartySelected: (DeviceSignIn) -> Unit = { dsi ->
        val selectPartyRequest = SelectPartyRequest(
            mspin = distributorLoginResult?.mspin,
            partyCode = dsi.PARTYCODE
        )
        viewModel.cdpLogger.logEvent(
            "MSGPA App Select Party",
            dsi.PARTYNAME!!,
            CDPTag.Action.EVENT_ACTION_CLICK
        )

        if (dsi.ACTIVEYN == "Y" || dsi.ACTIVEYN == "") {
            viewModel.selectPartyAuthenticate(selectPartyRequest).observe(this) { result ->
                result.loading {
                    binding.lottieProgress.apply {
                        playAnimation()
                        visible()
                    }
                }.success { response ->
                    viewModel.setSelectedParty(dsi)

                    when (response?.result?.loggedInUserData?.first()?.preferredLang) {
                        "en" -> preferenceHelper.setLanguage(0)
                        "hi" -> preferenceHelper.setLanguage(1)
                        "bn" -> preferenceHelper.setLanguage(2)
                        "kn" -> preferenceHelper.setLanguage(3)
                        "ml" -> preferenceHelper.setLanguage(4)
                        "ta" -> preferenceHelper.setLanguage(5)
                        "te" -> preferenceHelper.setLanguage(6)
                    }

                    viewModel.cdpLogger.submitMSGPProfile(
                        active_yn = dsi.ACTIVEYN!!,
                        city_cd = dsi.CITYCD!!,
                        dsi.CITYNAME!!,
                        dsi.CONTACTPERSON!!,
                        dsi.DEALERMAPCD!!,
                        dsi.MOBILE!!,
                        dsi.MULDEALERCD!!,
                        dsi.PARTYCODE!!,
                        dsi.PARTYNAME!!,
                        dsi.PARTYTYPE!!,
                        dsi.PARTYPIN!!,
                        "",
                        dsi.REGIONNAME!!,
                        dsi.STATENAME!!,
                        "DSC",
                    )
                    startNewActivity<HomeActivity> {
                        putExtra("productID", "null")
                    }
                    finish()
                }.fail { errorMessage, _ ->
                    showToast(0, "$errorMessage", ToastyType.NEGATIVE)
                    binding.lottieProgress.apply {
                        pauseAnimation()
                        invisible()
                    }
                }
            }
        } else {
            showSweetAlertDialog(
                message = getString(R.string.excedding_credit_limit),
                dialogType = SweetAlertDialog.WARNING_TYPE,
                buttonPositive = getString(R.string.ok),
                onPositiveClick = {
                    it.dismissWithAnimation()
                }, onNegativeClick = {

                }
            )

        }

    }

    override fun publishSearchResult(partyFilterList: java.util.ArrayList<DeviceSignIn>) {
        this.distributorList = partyFilterList
        val count = partyFilterList.size
        binding.recordCount.visibility = View.VISIBLE
        binding.recordCount.text = "Record Found : $count"
        if (count > 0) {
            binding.noResultFound.visibility = View.GONE
        } else {
            binding.noResultFound.visibility = View.VISIBLE
        }
    }

    override fun totalRecord(count: Int) {
        binding.recordCount.visibility = View.VISIBLE
        binding.recordCount.text = "Record Found : $count"
        if (count > 0) {
            binding.noResultFound.visibility = View.GONE
        } else {
            binding.noResultFound.visibility = View.VISIBLE
        }
    }

    override fun copiedNumber(number: String) {
        val clipboardManager = this.getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
        val clipData = ClipData.newPlainText("nonsense_data", number)
        clipboardManager.setPrimaryClip(clipData)
        showToast(0, resources.getString(R.string.copied_to_clipboard), ToastyType.POSITIVE)
        viewModel.cdpLogger.logEvent(
            "MSGPA App Party Mobile",
            "Copy the party mobile number",
            CDPTag.Action.EVENT_ACTION_CLICK
        )
    }

    override fun updatePartyLocation(
        deviceSignIn: DeviceSignIn,
        itemView: ItemDistributorListBinding
    ) {
        this.deviceSignIn = deviceSignIn
        this.itemView = itemView
        getLocation()
    }

    override fun getDirection(partyFilterList: ArrayList<DeviceSignIn>, position: Int) {

        Log.d("CurrentPosition", Gson().toJson(partyFilterList[position]))
        var lat = partyFilterList[position].LATITUDE
        var lon = partyFilterList[position].LONGITUDE
        val gmmIntentUri = Uri.parse("google.navigation:q=" + lat + "," + lon)
        val mapIntent = Intent(Intent.ACTION_VIEW, gmmIntentUri)
        mapIntent.setPackage("com.google.android.apps.maps")
        startActivity(mapIntent)
    }


    override fun infoSales(deviceSignIn: DeviceSignIn) {
        /* CONSTANTS.commonDialog(this@SelectPartyActivity,"Sales Achievement","% achievement is calculated basis the MTD sales of current month compared with avg", onPositiveClick = {
             it.dismiss()
         })*/


        showSweetAlertDialog(
            message = "% achievement is calculated basis the MTD sales of current month compared with avg sales of last 3 months",
            dialogType = SweetAlertDialog.NORMAL_TYPE,
            buttonPositive = getString(R.string.ok),
            onPositiveClick = {
                it.dismissWithAnimation()
            }, onNegativeClick = {

            }
        )
    }


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 1056) {
            if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                getLocation()
            }
        }
    }

    private fun updateLocation(updateGeoLocationRequest: UpdateGeoLocationRequest) {
        viewModel.updateGeoLocation(updateGeoLocationRequest).observe(this) { result ->
            result.loading {
                binding.lottieProgress.apply {
                    playAnimation()
                    visible()
                }
            }.success { response ->
                binding.lottieProgress.apply {
                    pauseAnimation()
                    invisible()
                }
                if (response != null) {

                    showToast(0, response.result.message!!, ToastyType.POSITIVE)
                    itemView.btnUpdateLocation.visibility = View.VISIBLE
                    //    itemView.btnUpdateLocation.text = "Punch In"
                    itemView.btnDirectionLocation.visibility = View.VISIBLE

                    itemView.btnUpdateLocation.apply {
                        background = null
                        tag = 1
                        setImageDrawable(
                            ContextCompat.getDrawable(
                                this@SelectPartyActivity,
                                R.drawable.ic_punch_in
                            )
                        )
                    }

                    itemView.lastVisitedTime.text = "Not yet visited"


                    distributorList.forEachIndexed { index, element ->
                        if (updateGeoLocationRequest.partyCode == element.PARTYCODE) {
                            distributorList[index] = element
                        }
                    }

                    searchAdapter.updateData(distributorList)
                    deviceSignInList(distributorLoginResult?.mspin.toString())
                }

            }.fail { errorMessage, _ ->
                showToast(0, "$errorMessage", ToastyType.NEGATIVE)
                binding.lottieProgress.apply {
                    pauseAnimation()
                    invisible()
                }
            }
        }
    }

    private fun updatePunchInLocation(updateGeoLocationRequest: UpdateGeoLocationRequest) {
        viewModel.updatePunchInLocation(updateGeoLocationRequest).observe(this) { result ->
            result.loading {
                itemView.btnUpdateLocation.isEnabled = false
                binding.lottieProgress.apply {
                    playAnimation()
                    visible()
                }
            }.success { response ->

                itemView.btnUpdateLocation.isEnabled = true

                binding.lottieProgress.apply {
                    pauseAnimation()
                    invisible()
                }
                if (response != null) {
                    showToast(0, response.result.message!!, ToastyType.POSITIVE)
                    itemView.btnUpdateLocation.visibility = View.GONE
                    itemView.lastVisitedTime.text = response.result.createdAt
                    itemView.btnDirectionLocation.visibility = View.VISIBLE
                    response.result.createdAt.toString()
                    deviceSignInList(distributorLoginResult?.mspin.toString())
                }

            }.fail { errorMessage, _ ->
                itemView.btnUpdateLocation.isEnabled = true

                showToast(0, "$errorMessage", ToastyType.NEGATIVE)
                binding.lottieProgress.apply {
                    pauseAnimation()
                    invisible()
                }
            }
        }
    }


    private fun checkPermissions(): Boolean {
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED
        ) {
            return true
        }
        return false
    }

    private fun requestPermissions() {
        ActivityCompat.requestPermissions(
            this,
            arrayOf(
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION
            ),
            1056
        )
    }

    @SuppressLint("MissingPermission", "SetTextI18n")
    private fun getLocation() {
        if (checkPermissions()) {
            if (isGPSEnabled()) {
                fusedLocationClient.lastLocation.addOnCompleteListener(this) { task ->
                    val location: Location? = task.result
                    if (location != null) {
                        deviceSignIn.LATITUDE = location.latitude.toString()
                        deviceSignIn.LONGITUDE = location.longitude.toString()
                        val updateGeoLocationRequest = UpdateGeoLocationRequest(
                            deviceSignIn.DEALERMAPCD!!,
                            deviceSignIn.MULDEALERCD!!,
                            deviceSignIn.locCd!!,
                            location.latitude.toString(),
                            location.longitude.toString(),
                            deviceSignIn.PARENTGROUP!!,
                            deviceSignIn.PARTYTYPE!!,
                            deviceSignIn.PARTYCODE!!,
                            distributorLoginResult!!.mspin!!,
                            deviceSignIn.REGIONCD!!
                        )

                        if (itemView.btnUpdateLocation.tag == 1) {
                            Log.e("punchin-", "Click")
                            updatePunchInLocation(updateGeoLocationRequest)
                            viewModel.cdpLogger.logEvent(
                                "MSGPA App Select Party - Sort By",
                                "Preffered Outlet - Punch In",
                                CDPTag.Action.EVENT_ACTION_CLICK
                            )


                        } else {
                            if (count == 0) {
                                count++
                                var builderDialog: androidx.appcompat.app.AlertDialog =
                                    GeoLocationUpdateDialog(
                                        this,
                                        onDialogOk = {
                                            count = 0
                                            updateLocation(updateGeoLocationRequest)
                                            viewModel.cdpLogger.logEvent(
                                                "MSGPA App Select Party - Sort By",
                                                "Preffered Outlet - Punch In Location",
                                                CDPTag.Action.EVENT_ACTION_CLICK
                                            )
                                        },
                                        onDialogCancil = {
                                            count = 0
                                        }
                                    )
                                builderDialog.setBuilderAndShow()
                            }


                        }

                    } else {
                        if (this::currentLocation.isInitialized) {
                            deviceSignIn.LATITUDE = location?.latitude.toString()
                            deviceSignIn.LONGITUDE = location?.longitude.toString()
                            val updateGeoLocationRequest = UpdateGeoLocationRequest(
                                deviceSignIn.DEALERMAPCD!!,
                                deviceSignIn.MULDEALERCD!!,
                                deviceSignIn.locCd!!,
                                location?.latitude.toString(),
                                location?.longitude.toString(),
                                deviceSignIn.PARENTGROUP!!,
                                deviceSignIn.PARTYTYPE!!,
                                deviceSignIn.PARTYCODE!!,
                                distributorLoginResult!!.mspin!!,
                                deviceSignIn.REGIONCD!!
                            )
                            if (itemView.btnUpdateLocation.tag == 1) {
                                updatePunchInLocation(updateGeoLocationRequest)

                                Log.e("punchin", "Click")


                            } else {

                                if (count == 0) {
                                    count++
                                    var builderDialog: androidx.appcompat.app.AlertDialog =
                                        GeoLocationUpdateDialog(
                                            this,
                                            onDialogOk = {
                                                updateLocation(updateGeoLocationRequest)
                                                count = 0
                                            },
                                            onDialogCancil = {
                                                count = 0
                                            }
                                        )
                                    builderDialog.setBuilderAndShow()
                                }


                            }

                        } else {
                            getUpdatedLocation()
                            showToast(
                                0,
                                getString(R.string.your_device_location_is_not_available_please_try_again),
                                ToastyType.NEGATIVE
                            )

                        }

                    }
                }
            } else {
                enableGpsSettings(
                    this,
                    getString(R.string.location),
                    getString(R.string.please_enable_the_location)
                )
            }
        } else {
            requestPermissions()
        }
    }


    private fun enableGpsSettings(context: Context, title: String, message: String) {
        val alertDialog: AlertDialog? = this.let {
            val builder = AlertDialog.Builder(context)
            builder.apply {
                setTitle(title)
                setMessage(message)
                setPositiveButton(R.string.ok,
                    DialogInterface.OnClickListener { dialog, id ->
                        // User clicked OK button
                        val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                        startActivity(intent)
                    })
                setNegativeButton(R.string.cancel,
                    DialogInterface.OnClickListener { dialog, id ->
                        // User cancelled the dialog
                    })
            }
            builder.create()
        }
        alertDialog?.show()
    }

    private lateinit var mLocationListener: LocationListener
    private fun getUpdatedLocation() {
        mLocationListener = object : LocationListener {
            override fun onLocationChanged(p0: Location) {
                currentLocation = p0
            }

            override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
            }
        }
        if (ActivityCompat.checkSelfPermission(
                this, Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                this, Manifest.permission.ACCESS_COARSE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            return
        }

        locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER, 5000, 50F,
            mLocationListener
        )

    }

    override fun onStop() {
        super.onStop()
        if (this::mLocationListener.isInitialized) {
            locationManager.removeUpdates(mLocationListener)
        }
    }
}