Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
14 kB
3
Indexable
Never
package org.transhelp.bykerr.uiRevamp.ui.activities

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import androidx.activity.result.ActivityResultLauncher
import androidx.core.app.ActivityCompat
import androidx.core.net.toUri
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView.AdapterDataObserver
import androidx.recyclerview.widget.SimpleItemAnimator
import org.transhelp.bykerr.R
import org.transhelp.bykerr.databinding.ActivityLocationSelectionBinding
import org.transhelp.bykerr.uiRevamp.helpers.*
import org.transhelp.bykerr.uiRevamp.helpers.listeners.LoadDataListener
import org.transhelp.bykerr.uiRevamp.helpers.listeners.SelectCityListener
import org.transhelp.bykerr.uiRevamp.lifecycleobserver.GpsDialogLifecycleObserver
import org.transhelp.bykerr.uiRevamp.models.CityModel
import org.transhelp.bykerr.uiRevamp.models.PageName
import org.transhelp.bykerr.uiRevamp.sharedPreferences.IPreferenceHelper
import org.transhelp.bykerr.uiRevamp.ui.adapters.AdapterSelectCity

class LocationSelectionActivity : BaseActivity(), SelectCityListener, LoadDataListener {
    init {
        GpsDialogLifecycleObserver(this)
    }
    private val locationPermission = arrayOf(
            "android.permission.ACCESS_FINE_LOCATION",
            "android.permission.ACCESS_COARSE_LOCATION"
    )
    private lateinit var binding: ActivityLocationSelectionBinding
    private var permissionResultSystemSetting: ActivityResultLauncher<Intent>? = null
    private lateinit var adapterSelectCity: AdapterSelectCity
    private lateinit var selectedCity: CityModel

    private var adapterDataObserver: AdapterDataObserver? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityLocationSelectionBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // if user manually goes to settings and enables permission
        initSystemSettingsListener()


        binding.layoutBtnContinue.btnActionWidthMatchParent.text = getString(R.string.str_continue)
        binding.layoutBtnAllowPermission.btnActionWidthWrapContent.text = getString(R.string.allow)

        binding.tvSkip.setOnClickListener {
            binding.layoutLocationAccess.visibility = View.GONE
            binding.layoutCitySelection.visibility = View.VISIBLE

        }

        binding.searchCity.setOnFocusChangeListener { view, focus ->
            if(focus)
            {
                val map=getCommonCleverTapProperty()
                map[AppConstants.CleverTapConstant.SCREEN_NAME] = PageName.LOCATION_SELECTION_PAGE.pageName
                recordCleverTapEvent(CleverTapConstants.CITY_SEARCH_CLICKED,map)
            }
        }

        binding.searchCity.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (this@LocationSelectionActivity::adapterSelectCity.isInitialized) {
                    adapterSelectCity.filter.filter(s)
                }
            }

            override fun afterTextChanged(s: Editable?) {
            }

        })

        binding.layoutBtnAllowPermission.btnActionWidthWrapContent.setOnClickListener {
            val intentAppSettings = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
            val uri = Uri.fromParts("package", this.packageName, null)
            intentAppSettings.data = uri
            permissionResultSystemSetting?.launch(intentAppSettings)
        }

        binding.layoutBtnContinue.btnActionWidthMatchParent.setOnClickListener {
            if (this::selectedCity.isInitialized) {
                val map=getCommonCleverTapProperty()
                map[AppConstants.CleverTapConstant.SCREEN_NAME] = PageName.LOCATION_SELECTION_PAGE.pageName
                recordCleverTapEvent(CleverTapConstants.CITY_CONTINUE_CLICKED,map)

                val manualCityObject = HashMap<String, Any>()
                manualCityObject["City Name"] = selectedCity.cityName ?: ""
                iPreferenceHelper.setSelectedCityObject(selectedCity)
                if (intent.getStringExtra(AppConstants.SHARED_URL) != null) {
                    launchRouteScreen(iPreferenceHelper)
                } else {
                    launchHomeScreen()
                }
            } else {
                if (iPreferenceHelper.getSelectedCityObject() == null) {
                    showToastShort(getString(R.string.pls_select_a_city))
                } else {
                    if (intent.getStringExtra(AppConstants.SHARED_URL) != null) {
                        launchRouteScreen(iPreferenceHelper)
                    } else {
                        launchHomeScreen()
                    }
                }
            }
        }

        binding.ivBack.setOnClickListener {
            onBackPressed()
        }



        checkNetworkAndFetchData()

    }

    fun showNoData(visible: Boolean = false) {
        binding.tvNoData.visibility = if (visible) {
                View.VISIBLE
            } else {
                View.GONE
            }
    }

    private fun checkNetworkAndFetchData() {
        if (ConnectivityManagerHelper.isNetworkAvailable(this)) {
            setCityList()
        } else {
            loadViewModel.isLoaded.value = false
        }
    }

    private fun setCityList() {
        getCityFromRemoteConfig { cityModelList ->

            binding.layoutBtnContinue.btnActionWidthMatchParent.isEnabled = cityModelList.isNotEmpty()

            for (city in cityModelList) {
                if (iPreferenceHelper.getSelectedCityObject()?.cityName.equals(city.cityName, true)) {
                    city.isSelected = true
                }
            }

            loadViewModel.isLoaded.value = true

            adapterSelectCity = AdapterSelectCity(cityModelList, this, iPreferenceHelper)
            binding.rvCityList.layoutManager = LinearLayoutManager(this)
            binding.rvCityList.adapter = adapterSelectCity
            (binding.rvCityList.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
            adapterDataObserver = object : AdapterDataObserver() {
                override fun onChanged() {
                    super.onChanged()
                    logit(adapterSelectCity.itemCount)
                    showNoData(adapterSelectCity.itemCount < 1)
                }
            }
            adapterSelectCity.registerAdapterDataObserver(adapterDataObserver as AdapterDataObserver)
        }
    }

    private fun requestLocationPermission() {
        if (!isGPSEnabled()) {
            showGPSEnablePopup()
        } else {
            when {
                hasPermissions(locationPermission) -> {
                    goToHomeScreen()
                }

                ActivityCompat.shouldShowRequestPermissionRationale(
                        this,
                        Manifest.permission.ACCESS_FINE_LOCATION
                ) &&
                        ActivityCompat.shouldShowRequestPermissionRationale(
                                this,
                                Manifest.permission.ACCESS_COARSE_LOCATION
                        ) -> {
                    binding.layoutLocationAccess.visibility = View.VISIBLE
                }

                else -> {
//                    requestPermissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION)
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        multiplePermissionActivityResultLauncher?.launch(locationPermission)
                    }
                    else{
                        binding.layoutLocationAccess.visibility = View.GONE
                    }
                }
            }
        }
    }


    private fun initSystemSettingsListener() {
        permissionResultSystemSetting = startActivityForResultLaunch { result ->
            if (!hasPermissions(locationPermission)
            ) {
                onPermissionAction(false)
            } else {
                onPermissionAction(true)
            }
        }
    }

    override fun onPermissionAction(isPermissionGranted: Boolean) {
        if (isPermissionGranted) {
            goToHomeScreen()
        } else {
            binding.layoutLocationAccess.visibility = View.VISIBLE
        }
    }

    override fun onCitySelected(cityModel: CityModel?) {
        if (cityModel != null) {
            selectedCity = CityModel(
                    cityModel.cityName,
                    cityModel.stateName,
                    cityModel.latitude,
                    cityModel.longitude,
                    true,
                    true,
                    cityModel.isBusPassBookingVisible,
                    isBusTicketBookingVisible = cityModel.isBusTicketBookingVisible,
                    isBusLiveTrackingEnabled = cityModel.isBusLiveTrackingEnabled ?: false
            )
            val map=getCommonCleverTapProperty()
            map[AppConstants.CleverTapConstant.SCREEN_NAME] = PageName.LOCATION_SELECTION_PAGE.pageName
            recordCleverTapEvent(CleverTapConstants.CITY_CITY_SELECTED,map)


        }
    }

    override fun onResume() {
        super.onResume()
        activity = this

        captureFirebaseScreenView(LocationSelectionActivity::class.java.simpleName)

//        if (isGPSEnabled()) {
//            checkLocationPermissionStatus()
//        }
        if (isGPSEnabled()) {
            if (intent.hasExtra(AppConstants.SELECT_CITY_CALLER_KEY)) {
                if (intent.getStringExtra(AppConstants.SELECT_CITY_CALLER_KEY)
                                .equals(AppConstants.SELECT_CITY_CALLER_VALUE_INTRO, true)
                ) {
                    if (!hasPermissions(locationPermission)
                    ) {
                        requestLocationPermission()
                    } else {
                        goToHomeScreen()
                    }
                } else if (intent.getStringExtra(AppConstants.SELECT_CITY_CALLER_KEY)
                                .equals(AppConstants.SELECT_CITY_CALLER_VALUE_HOME, true)
                ) {
                    binding.layoutCitySelection.visibility = View.VISIBLE
                    binding.ivBird2.visibility = View.GONE
                    binding.tvSelectCity.visibility = View.GONE
                    binding.ivBack.visibility = View.VISIBLE
                    binding.tvTitle.visibility = View.VISIBLE
                } else if (intent.getStringExtra(AppConstants.SELECT_CITY_CALLER_KEY)
                                .equals(AppConstants.SELECT_CITY_CALLER_VALUE_HOME_UNSERVICEABLE_CITY, true)
                ) {
                    binding.layoutCitySelection.visibility = View.VISIBLE
                    binding.ivBird2.visibility = View.VISIBLE
                    binding.tvSelectCity.visibility = View.VISIBLE
                    binding.ivBack.visibility = View.VISIBLE
                    binding.tvTitle.visibility = View.VISIBLE
                    val unserviceableCityName =
                            intent.getStringExtra(AppConstants.SELECT_CITY_EXTRA_DATA_KEY)
                    binding.tvSelectCity.text = getString(R.string.label_out_of_service_area)
                }
            }
        } else {
            showGPSEnablePopup()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (this@LocationSelectionActivity::adapterSelectCity.isInitialized) {
            adapterDataObserver?.let { adapterSelectCity.unregisterAdapterDataObserver(it) }
        }
    }

    override fun checkLoadData() {
        if (loadViewModel.isLoaded.value == false) {
            checkNetworkAndFetchData()
        }
    }

    companion object {
        fun Activity.launchRouteScreen(iPreferenceHelper: IPreferenceHelper) {
            if (iPreferenceHelper.getCustomerID().isEmpty()) {
                startActivity(Intent(this, HomeActivity::class.java).apply {
                    flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
                    putExtra(
                            AppConstants.SHARED_URL,
                            intent.getStringExtra(AppConstants.SHARED_URL)
                    )
                })
                finish()
            } else {
                val routeIntent = Intent(this, RouteSuggestionsActivity::class.java)
                routeIntent.data = intent.getStringExtra(AppConstants.SHARED_URL)?.toUri()
                routeIntent.putExtra(AppConstants.LAST_PRIMARY_SOURCE,PageName.LOCATION_SELECTION_PAGE.pageName)
                routeIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
                startActivity(routeIntent)
                finish()
            }
        }


        private fun Activity.launchHomeScreen() {
            val intent = Intent(this, HomeActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
            startActivity(intent)
            finish()
        }
    }
}