Advertisement
Guest User

Untitled

a guest
Sep 10th, 2018
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 9.94 KB | None | 0 0
  1. package finance.robo.android.offices.ui.map
  2.  
  3. import android.Manifest
  4. import android.annotation.SuppressLint
  5. import android.content.pm.PackageManager
  6. import android.graphics.Color
  7. import android.location.Location
  8. import android.location.LocationListener
  9. import android.location.LocationManager
  10. import android.net.Uri
  11. import android.os.Bundle
  12. import android.support.design.widget.BottomSheetBehavior
  13. import android.support.v4.app.ActivityCompat
  14. import android.support.v4.content.ContextCompat
  15. import android.view.LayoutInflater
  16. import android.view.View
  17. import android.view.ViewGroup
  18. import android.widget.Toast
  19. import com.arellomobile.mvp.presenter.InjectPresenter
  20. import com.arellomobile.mvp.presenter.PresenterType
  21. import com.arellomobile.mvp.presenter.ProvidePresenter
  22. import com.arellomobile.mvp.presenter.ProvidePresenterTag
  23. import com.facebook.drawee.backends.pipeline.Fresco
  24. import com.facebook.imagepipeline.common.ResizeOptions
  25. import com.facebook.imagepipeline.request.ImageRequestBuilder
  26. import com.google.android.gms.location.FusedLocationProviderClient
  27. import com.google.android.gms.location.LocationServices
  28. import com.google.android.gms.maps.CameraUpdateFactory
  29. import com.google.android.gms.maps.GoogleMap
  30. import com.google.android.gms.maps.OnMapReadyCallback
  31. import com.google.android.gms.maps.SupportMapFragment
  32. import com.google.android.gms.maps.model.*
  33. import finance.robo.android.core.analytics.IAnalytic
  34. import finance.robo.android.core.analytics.RoutesTags
  35. import finance.robo.android.core.base.BaseFragment
  36. import finance.robo.android.core.baseComponentsProvider
  37. import finance.robo.android.core.permissions.PermissionInstructionDialog
  38. import finance.robo.android.core.permissions.PermissionsUtils
  39. import finance.robo.android.offices.R
  40. import finance.robo.android.offices.di.DaggerOfficesComponent
  41. import finance.robo.android.offices.entity.Office
  42. import finance.robo.android.offices.presentation.OfficesPresenter
  43. import finance.robo.android.offices.presentation.OfficesView
  44. import kotlinx.android.synthetic.main.fragment_offices_map.*
  45. import kotlinx.android.synthetic.main.fragment_offices_map.view.*
  46. import javax.inject.Inject
  47.  
  48. class OfficesMapFragment : BaseFragment(), OfficesView, OnMapReadyCallback {
  49.  
  50.     lateinit var fusedLocationClient: FusedLocationProviderClient
  51.     lateinit var lastKnownLocation: Location
  52.  
  53.     companion object {
  54.         @JvmStatic
  55.         fun newInstance(routingTag: String? = null): OfficesMapFragment {
  56.             val fragment = OfficesMapFragment()
  57.             fragment.arguments = Bundle().apply { putString(RoutesTags.ROUTER_KEY, routingTag) }
  58.             return fragment
  59.         }
  60.     }
  61.  
  62.     private var isMapReady = false
  63.     private lateinit var map: GoogleMap
  64.     private var offices = listOf<Office>()
  65.     private lateinit var bottomSheetBehavior: BottomSheetBehavior<ViewGroup>
  66.     private lateinit var mapFragment: SupportMapFragment
  67.  
  68.     @Inject
  69.     lateinit var analytics: IAnalytic
  70.  
  71.     @Inject
  72.     @InjectPresenter(type = PresenterType.WEAK)
  73.     lateinit var officesPresenter: OfficesPresenter
  74.  
  75.     @ProvidePresenter(type = PresenterType.WEAK)
  76.     fun provideOfficesPresenter() = officesPresenter
  77.  
  78.     @ProvidePresenterTag(type = PresenterType.WEAK, presenterClass = OfficesPresenter::class)
  79.     fun provideOfficePresenterTag() = "OfficesPresenter"
  80.  
  81.     override fun inject() {
  82.         DaggerOfficesComponent
  83.                 .builder()
  84.                 .commonComponent(context!!.baseComponentsProvider().provideCommonComponent())
  85.                 .build()
  86.                 .inject(this)
  87.         officesPresenter.routingTag = arguments?.getString(RoutesTags.ROUTER_KEY)
  88.     }
  89.  
  90.     override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
  91.         return inflater.inflate(R.layout.fragment_offices_map, container, false)
  92.     }
  93.  
  94.     override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
  95.         super.onViewCreated(view, savedInstanceState)
  96.         mapFragment = childFragmentManager.findFragmentById(R.id.mapFragment) as SupportMapFragment
  97.         mapFragment.getMapAsync(this)
  98.         bottomSheetBehavior = BottomSheetBehavior.from(view.officeInfoPanel)
  99. //        mapFragment.view?.findViewById<View>(Integer.parseInt("1"))?.parent?.let { parentView -> (parentView as View).findViewById<View>(Integer.parseInt("2"))?.performClick() }
  100.     }
  101.  
  102.     override fun onMapReady(map: GoogleMap) {
  103.         isMapReady = true
  104.         this.map = map
  105.         map.setOnMarkerClickListener { marker ->
  106.             findOfficeByAddress(marker.title)?.let { office -> showOfficeInfo(office) }
  107.             true
  108.         }
  109.         map.setOnMapClickListener { collapseInfoPanel() }
  110.         setMapMarkers(offices)
  111.         closeButton.setOnClickListener { collapseInfoPanel() }
  112.  
  113.         map.setOnMyLocationButtonClickListener { false }
  114.         permissionDialog()
  115.  
  116.     }
  117.  
  118.     @SuppressLint("MissingPermission")
  119.     override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
  120.         super.onRequestPermissionsResult(requestCode, permissions, grantResults)
  121.         if (requestCode == PermissionsUtils.REQUEST_ACCESS_FINE_LOCATION && permissions.isNotEmpty()) {
  122.             if (PermissionsUtils.hasPermission(fragmentContext, permissions[0])) {
  123.                 map.isMyLocationEnabled = true
  124.                 mapFragment.view?.findViewById<View>(Integer.parseInt("1"))?.parent?.let { parentView -> (parentView as View).findViewById<View>(Integer.parseInt("2"))?.performClick() }
  125.             } else {
  126.                 permissionDialog()
  127.             }
  128.         }
  129.     }
  130.  
  131.     override fun showLoadingError(details: Map<String, List<String>>) {
  132.         showMessage(getString(R.string.error_offices_loading))
  133.     }
  134.  
  135.     override fun showProgress(show: Boolean) {
  136.  
  137.     }
  138.  
  139.     override fun showItemsAdded(index: Int, count: Int, showMoreButton: Boolean) {
  140.         setMapMarkers(offices)
  141.     }
  142.  
  143.     override fun updateEmptyView(imageRes: Int?, message: String?) {
  144.  
  145.     }
  146.  
  147.     override fun clearAll() {
  148.     }
  149.  
  150.     override fun showMoreProgress() {
  151.  
  152.     }
  153.  
  154.     override fun hideMoreProgress() {
  155.  
  156.     }
  157.  
  158.     override fun showNetworkError() {
  159.         //Empty implementation
  160.     }
  161.  
  162.     override fun bindData(data: List<Office>) {
  163.         offices = data
  164.     }
  165.  
  166.     @SuppressLint("MissingPermission")
  167.     fun permissionDialog() {
  168.         val permissionDialog = PermissionInstructionDialog.newInstance(
  169.                 R.string.permission_dialog_map_message,
  170.                 arrayListOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION),
  171.                 PermissionsUtils.REQUEST_ACCESS_FINE_LOCATION
  172.         )
  173.         if (!permissionDialog.showIfRequired(activity?.supportFragmentManager!!, fragmentContext)) {
  174.             map.isMyLocationEnabled = true
  175.             //лайфхах от Витали :)
  176.             mapFragment.view?.findViewById<View>(Integer.parseInt("1"))?.parent?.let { parentView -> (parentView as View).findViewById<View>(Integer.parseInt("2"))?.performClick() }
  177.         }
  178.     }
  179.  
  180.     @SuppressLint("MissingPermission")
  181.     private fun setMapMarkers(offices: List<Office>) {
  182.         if (!isMapReady || offices.isEmpty()) {
  183.             return
  184.         }
  185.         val builder = LatLngBounds.Builder()
  186.         offices
  187.                 .filter { office -> office.address.latitude != null && office.address.longitude != null }
  188.                 .forEach { office ->
  189.                     office.address.let { address ->
  190.                         val marker = MarkerOptions()
  191.                                 .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_marker))
  192.                                 .position(LatLng(address.latitude!!.toDouble(), address.longitude!!.toDouble()))
  193.                                 .title(address.full)
  194.                         map.addMarker(marker)
  195.                         builder.include(marker.position)
  196.                     }
  197.                 }
  198.  
  199.         map.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 0))
  200.     }
  201.  
  202.     @SuppressLint("MissingPermission")
  203.     fun getDeviceLoacation() {
  204. //        context?.let { fusedLocationClient = LocationServices.getFusedLocationProviderClient(it) }
  205. //        val locationResult = fusedLocationClient.lastLocation
  206. //        locationResult.addOnCompleteListener { task ->
  207. //            if (task.isSuccessful) {
  208. //                lastKnownLocation = task.result
  209. //                map.moveCamera(CameraUpdateFactory.newLatLng(LatLng(lastKnownLocation.latitude, lastKnownLocation.longitude)))
  210. //            }
  211. ////            else {
  212. ////                map.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 0))
  213. ////                map.uiSettings.isMyLocationButtonEnabled = false
  214. ////            }
  215. //        }
  216.     }
  217.  
  218.     private fun showOfficeInfo(office: Office) {
  219.         address.text = office.address.full
  220.         workTime.text = office.workingTime
  221.         office.photoUrl?.let { url ->
  222.             val imageRequest = ImageRequestBuilder.newBuilderWithSource(Uri.parse(url))
  223.                     .setResizeOptions(ResizeOptions(photo.width, photo.height))
  224.                     .build()
  225.             photo.controller = Fresco.newDraweeControllerBuilder()
  226.                     .setOldController(photo.controller)
  227.                     .setImageRequest(imageRequest)
  228.                     .build()
  229.         }
  230.         expandInfoPanel()
  231.     }
  232.  
  233.     private fun expandInfoPanel() {
  234.         if (bottomSheetBehavior.state != BottomSheetBehavior.STATE_EXPANDED)
  235.             bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED
  236.     }
  237.  
  238.  
  239.     private fun collapseInfoPanel() {
  240.         if (bottomSheetBehavior.state == BottomSheetBehavior.STATE_EXPANDED)
  241.             bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
  242.     }
  243.  
  244.     private fun findOfficeByAddress(address: String) = offices.firstOrNull { office -> office.address.full == address }
  245. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement