-
Notifications
You must be signed in to change notification settings - Fork 5
/
MainActivity.kt
932 lines (814 loc) · 36.5 KB
/
MainActivity.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
package com.flexicharge.bolt.activities
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.location.Location
import android.os.Bundle
import android.transition.ChangeBounds
import android.transition.Fade
import android.transition.TransitionManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import android.view.inputmethod.InputMethodManager
import android.widget.*
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.content.res.AppCompatResources
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.widget.doOnTextChanged
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chaos.view.PinView
import com.flexicharge.bolt.R
import com.flexicharge.bolt.SpacesItemDecoration
import com.flexicharge.bolt.activities.businessLogic.*
import com.flexicharge.bolt.adapters.ChargePointListAdapter
import com.flexicharge.bolt.adapters.ChargersListAdapter
import com.flexicharge.bolt.adapters.TimeCalculation
import com.flexicharge.bolt.api.flexicharge.ChargePoints
import com.flexicharge.bolt.api.flexicharge.Charger
import com.flexicharge.bolt.api.flexicharge.TransactionSession
import com.flexicharge.bolt.databinding.ActivityMainBinding
import com.flexicharge.bolt.foregroundServices.ChargingService
import com.flexicharge.bolt.helpers.LoginChecker
import com.flexicharge.bolt.helpers.MapHelper
import com.flexicharge.bolt.helpers.MapHelper.addNewMarkers
import com.flexicharge.bolt.helpers.MapHelper.currLocation
import com.flexicharge.bolt.helpers.MapHelper.currentLocation
import com.flexicharge.bolt.helpers.MapHelper.fetchLocation
import com.flexicharge.bolt.helpers.MapHelper.panToPos
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.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.button.MaterialButton
import java.util.*
import kotlin.collections.ArrayList
import kotlin.math.roundToInt
import kotlinx.coroutines.*
class MainActivity :
AppCompatActivity(),
OnMapReadyCallback,
ChargePointListAdapter.ShowChargePointInterface,
ChargersListAdapter.ChangeInputInterface {
private lateinit var binding: ActivityMainBinding // the bindings in the Main Activity (camera, user, charger, position).
private lateinit var chargerInputDialog: BottomSheetDialog
private lateinit var paymentSummaryDialog: BottomSheetDialog
private lateinit var pinView: PinView
private lateinit var chargerInputStatus: MaterialButton
private lateinit var listOfChargersRecyclerView: RecyclerView
private var isBottomSheetVisible = false
private val timeCalculation = TimeCalculation()
private companion object {
const val REMOTE_CHARGERS_REFRESH_INTERVAL_MS: Long = 10000
}
private val remoteChargers = RemoteChargers()
private val remoteChargePoints = RemoteChargePoints()
private val currentRemoteTransaction = RemoteTransaction()
private val remoteChargersRefresher =
RemoteObjectRefresher(remoteChargers, REMOTE_CHARGERS_REFRESH_INTERVAL_MS)
override fun onCreate(savedInstanceState: Bundle?) {
checkPendingTransaction()
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
remoteChargers.setOnRefreshedCallBack {
lifecycleScope.launch(Dispatchers.Main) {
addNewMarkers(
this@MainActivity,
remoteChargers.value,
fun(charger: Charger?): Boolean {
if (charger != null && validateChargerId(charger.connectorID.toString())) {
lifecycleScope.launch(Dispatchers.Main) {
setupChargerInputDialog(charger.connectorID)
}
}
return false
}
)
}
}
remoteChargersRefresher.run(lifecycleScope)
binding.mainActivityButtonPinPosition.setOnClickListener {
currLocation(this)
}
val resultLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == Activity.RESULT_OK) {
val data: Intent? = it.data
try {
setupChargerInputDialog()
changeInput(data?.getStringExtra("QR_SCAN_RESULT").toString())
} catch (e: Exception) {
Toast.makeText(this, e.message, Toast.LENGTH_SHORT)
.show() // exception handling
}
}
}
binding.mainActivityButtonCamera.setOnClickListener {
val intent = Intent(this, QrActivity::class.java)
resultLauncher.launch(intent)
}
val mapFragment =
supportFragmentManager.findFragmentById(R.id.mainActivity_fragment_map) as SupportMapFragment
mapFragment.getMapAsync(this)
binding.mainActivityButtonIdentifyCharger.setOnClickListener {
setupChargerInputDialog()
}
val loginSharedPref = getSharedPreferences("loginPreference", Context.MODE_PRIVATE)
val accessToken = loginSharedPref.getString("accessToken", Context.MODE_PRIVATE.toString())
val userId = loginSharedPref.getString("userId", Context.MODE_PRIVATE.toString())
if (accessToken != null) {
currentRemoteTransaction.localAccessToken = accessToken
}
binding.mainActivityButtonUser.setOnClickListener {
if (LoginChecker.LOGGED_IN) {
val intent = Intent(this, ProfileMenuLoggedInActivity::class.java)
intent.putExtra("accessToken", accessToken)
intent.putExtra("userId", userId)
startActivity(intent)
} else {
startActivity(Intent(this, RegisterActivity::class.java))
}
}
}
override fun onResume() { // Called after onRestoreInstanceState, onRestart, or onPause
super.onResume()
Log.d("StartVerify", "On resume")
val loginSharedPref = getSharedPreferences("loginPreference", Context.MODE_PRIVATE)
val accessToken = loginSharedPref.getString("accessToken", Context.MODE_PRIVATE.toString())
if (accessToken != null) {
currentRemoteTransaction.localAccessToken = accessToken
}
remoteChargersRefresher.run(lifecycleScope)
val refreshChargers = remoteChargers.refresh(lifecycleScope)
refreshChargers.invokeOnCompletion {
if (refreshChargers.isCancelled) {
return@invokeOnCompletion
}
}
val refreshChargePoints = remoteChargePoints.refresh(lifecycleScope)
refreshChargePoints.invokeOnCompletion {
if (refreshChargePoints.isCancelled) {
return@invokeOnCompletion
}
}
if (!isBottomSheetVisible) {
Log.d("StartVerify", "Check Pending transaction")
checkPendingTransaction()
}
fetchLocation(this)
}
override fun changeInput(newInput: String) {
pinView.setText(newInput)
}
override fun showChargePoint(
latitude: Double,
longitude: Double,
chargePointID: Int
) {
panToPos(latitude, longitude)
showCheckout(true, chargePointID, false, -1)
}
override fun onMapReady(googleMap: GoogleMap) {
MapHelper.onMapReady(this, googleMap)
}
private fun Context.hideKeyboard(view: View) {
val inputMethodManager =
getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
}
private fun stopChargingProcess(
bottomSheetDialog: BottomSheetDialog
) {
// currentRemoteTransaction.refresh(lifecycleScope)
try {
val stopRemoteTransactionJob = currentRemoteTransaction.stop(lifecycleScope)
stopRemoteTransactionJob.invokeOnCompletion {
if (stopRemoteTransactionJob.isCancelled) {
return@invokeOnCompletion
}
lifecycleScope.launch(Dispatchers.Main) {
Intent(applicationContext, ChargingService::class.java).also {
it.action = ChargingService.Actions.STOP.toString()
startService(it)
}
val dateTime =
timeCalculation.unixToDateTime(
currentRemoteTransaction.value.endTimestamp!!
)
Log.d("EndVerify3", dateTime)
val sharedPreferences =
getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE)
sharedPreferences.edit().apply { putInt("TransactionId", -1) }.apply()
bottomSheetDialog.dismiss()
displayPaymentSummaryDialog(dateTime)
}
}
} catch (e: Exception) {
lifecycleScope.launch(Dispatchers.Main) {
Toast.makeText(applicationContext, e.message, Toast.LENGTH_LONG).show()
val sharedPreferences = getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE)
sharedPreferences.edit().apply { putInt("TransactionId", -1) }.apply()
bottomSheetDialog.dismiss()
// displayPaymentSummaryDialog(dateTime)
}
}
}
private val scope = CoroutineScope(Dispatchers.IO)
private var isPolling = false
private fun setupChargingInProgressDialog() {
if (this::chargerInputDialog.isInitialized) {
Log.d("CheckTransaction", "it is initialized")
chargerInputDialog.dismiss()
}
val retrieveJob =
currentRemoteTransaction.retrieve(lifecycleScope)
try {
retrieveJob.invokeOnCompletion {
if (retrieveJob.isCancelled) {
Log.d("StartVerify", "retrieve job cancelled")
return@invokeOnCompletion
}
}
} catch (e: Exception) {
Log.d("StartVerify", "catch error remote trans")
println("Error when retrieving")
}
val bottomSheetDialog = BottomSheetDialog(this@MainActivity)
val bottomSheetView = LayoutInflater.from(applicationContext).inflate(
R.layout.layout_charger_in_progress,
findViewById<ConstraintLayout>(R.id.chargerInProgress)
)
val progressbarPercent =
bottomSheetView.findViewById<TextView>(
R.id.chargeInProgressLayout_textView_progressbarPercent
)
val progressbar =
bottomSheetView.findViewById<ProgressBar>(R.id.chargeInProgressLayout_progressBar)
val chargeSpeed =
bottomSheetView.findViewById<TextView>(R.id.chargeInProgressLayout_textView_chargeSpeed)
val location =
bottomSheetView.findViewById<TextView>(R.id.chargeInProgressLayout_textView_location)
val chargeDuration = bottomSheetView.findViewById<TextView>(
R.id.chargeInProgressLayout_textview_chargingTimeStatus
)
bottomSheetDialog.behavior.state = BottomSheetBehavior.STATE_EXPANDED
bottomSheetDialog.behavior.isDraggable = false
bottomSheetDialog.setCancelable(false)
val currentPercentage = currentRemoteTransaction.value.currentChargePercentage
progressbar.progress = currentPercentage!!
isPolling = true
val foundCharger =
remoteChargers.value.find { it.connectorID == currentRemoteTransaction.value.connectorID }
val currentChargePoint =
remoteChargePoints.value.find { it.chargePointID == foundCharger?.chargePointID }
location.text = currentChargePoint?.name
scope.launch {
while (isPolling) {
currentRemoteTransaction.retrieve(lifecycleScope)
withContext(Dispatchers.Main) {
if (currentRemoteTransaction.value.endTimestamp != null) {
isPolling = false
stopChargingProcess(bottomSheetDialog)
} else {
if (currentRemoteTransaction.value.startTimestamp != null) {
val currentTime = System.currentTimeMillis()
val duration = timeCalculation.checkDuration(
currentRemoteTransaction.value.startTimestamp!! * 1000,
currentTime
)
chargeDuration.text = duration
} else {
// chargeDuration.text = chargeDuration.text
}
progressbar.progress =
currentRemoteTransaction.value.currentChargePercentage!!
progressbarPercent.text =
currentRemoteTransaction.value.currentChargePercentage.toString()
chargeSpeed.text = currentRemoteTransaction.value.kwhTransferred.toString()
}
}
delay(3000)
}
}
bottomSheetView.findViewById<MaterialButton>(
R.id.chargeInProgressLayout_button_stopCharging
)
.setOnClickListener {
isPolling = false
stopChargingProcess(bottomSheetDialog)
}
bottomSheetDialog.setContentView(bottomSheetView)
isBottomSheetVisible = true
bottomSheetDialog.show()
}
private fun displayPaymentSummaryDialog(dateTime: String) {
Log.d("EndVerify1234", "we get here")
if (this::paymentSummaryDialog.isInitialized) {
paymentSummaryDialog.dismiss()
}
// TODO Look over values before final commit
paymentSummaryDialog = BottomSheetDialog(this@MainActivity, R.style.BottomSheetDialogTheme)
val bottomSheetView = LayoutInflater.from(applicationContext).inflate(
R.layout.layout_payment_summary,
findViewById<ConstraintLayout>(R.id.paymentSummaryLayout)
)
val energyUsedTextView =
bottomSheetView.findViewById<TextView>(
R.id.paymentSummaryLayout_textView_energyUsedValue
)
val durationTextView =
bottomSheetView.findViewById<TextView>(R.id.paymentSummaryLayout_textView_durationValue)
val chargingStopTimeTextView =
bottomSheetView.findViewById<TextView>(R.id.paymentSummaryLayout_textView_finishedTime)
val totalCostTextView =
bottomSheetView.findViewById<TextView>(R.id.paymentPriceLayout_textView_price)
val crossButton =
bottomSheetView.findViewById<ImageButton>(R.id.paymentSummaryLayout_button_close)
crossButton.setOnClickListener {
paymentSummaryDialog.dismiss()
isBottomSheetVisible = false
}
Log.d("EndVerify666", currentRemoteTransaction.value.toString())
val transaction = currentRemoteTransaction.value
val kwhTransferred = transaction.kwhTransferred
val totalCost = transaction.price?.toFloat()?.div(100)
val pricePerKwh = totalCost?.div(transaction.kwhTransferred!!)
val duration = timeCalculation.checkDuration(
transaction.startTimestamp!! * 1000,
transaction.endTimestamp!! * 1000
)
var roundedPrice = 0.0
var roundedKwh = 0.0
if (pricePerKwh != null) {
roundedPrice = String.format(Locale.US, "%.2f", pricePerKwh).toDouble()
roundedKwh = String.format(Locale.US, "%.2f", kwhTransferred).toDouble()
}
val rounded = (pricePerKwh?.times(100))?.toFloat()?.div(100)
lifecycleScope.launch(Dispatchers.Main) {
val energyUsedText = "$roundedKwh kWh @ $roundedPrice + kr kWh"
val chargingStopTimeText = "Charging stopped at $dateTime"
val totalCostText = "$totalCost kr"
energyUsedTextView.text = energyUsedText
durationTextView.text = duration
chargingStopTimeTextView.text = chargingStopTimeText
totalCostTextView.text = totalCostText
paymentSummaryDialog.setContentView(bottomSheetView)
paymentSummaryDialog.show()
}
}
private fun setupChargerInputDialog(chargerId: Int? = null) {
chargerInputDialog = BottomSheetDialog(
this@MainActivity,
R.style.BottomSheetDialogTheme
)
val bottomSheetView = LayoutInflater.from(applicationContext).inflate(
R.layout.layout_charger_input,
findViewById<ConstraintLayout>(R.id.chargerInputLayout)
)
val arrow =
bottomSheetView.findViewById<ImageView>(R.id.chargePointsNearMeLayout_imageView_arrow)
arrow.setOnClickListener {
displayChargePointList(bottomSheetView, arrow)
}
val backButton = bottomSheetView.findViewById<ImageButton>(R.id.checkoutLayout_button_back)
backButton.setOnClickListener {
showCheckout(false, -1, false, -1)
}
setupChargerInput(bottomSheetView, chargerId)
chargerInputDialog.setContentView(bottomSheetView)
chargerInputDialog.show()
}
private fun setupChargerInput(bottomSheetView: View, chargerId: Int? = null) {
Log.d("displayChargerList", "displayChargerList")
pinView = bottomSheetView.findViewById(R.id.chargerInputLayout_pinView_chargerInput)
chargerInputStatus =
bottomSheetView.findViewById(R.id.chargerInputLayout_textView_chargerStatus)
if (chargerId != null) {
if (validateChargerId(chargerId.toString())) {
pinView.setText(chargerId.toString())
displayChargerStatus(chargerId, chargerInputStatus)
}
}
pinView.doOnTextChanged { text, _, _, _ ->
if (text?.length == 6) {
val newChargerId = text.toString().toUInt().toInt()
if (validateChargerId(text.toString())) {
displayChargerStatus(newChargerId, chargerInputStatus)
hideKeyboard(bottomSheetView)
} else {
setChargerButtonStatus(
chargerInputStatus,
false,
"ChargerId has to consist of 6 digits",
0
)
hideKeyboard(bottomSheetView)
}
}
}
}
private fun displayChargerList(bottomSheetView: View, chargePointId: Int) {
val chargerId = pinView.text.toString()
val refreshJob = remoteChargers.refresh(lifecycleScope)
refreshJob.invokeOnCompletion {
if (refreshJob.isCancelled) {
return@invokeOnCompletion
}
}
val refreshRemoteChargePointsJob = remoteChargePoints.refresh(lifecycleScope)
refreshRemoteChargePointsJob.invokeOnCompletion {
if (refreshRemoteChargePointsJob.isCancelled) {
return@invokeOnCompletion
}
lifecycleScope.launch(Dispatchers.Main) {
listOfChargersRecyclerView =
bottomSheetView.findViewById(R.id.checkoutLayout_recyclerView_chargerList)
listOfChargersRecyclerView.layoutManager = LinearLayoutManager(
this@MainActivity,
LinearLayoutManager.HORIZONTAL,
false
)
val chargersInCp = remoteChargers.value.filter { it.chargePointID == chargePointId }
listOfChargersRecyclerView.adapter =
ChargersListAdapter(chargersInCp, chargerId, this@MainActivity)
// Only add decoration on first-time display
if (listOfChargersRecyclerView.itemDecorationCount == 0) {
listOfChargersRecyclerView.addItemDecoration(SpacesItemDecoration(15))
}
}
}
}
private fun displayChargePointList(bottomSheetView: View, arrow: ImageView) {
val listOfChargePointsRecyclerView =
bottomSheetView.findViewById<RecyclerView>(
R.id.chargePointsNearMeLayout_recyclerView_chargePointList
)
val chargePointsNearMe =
bottomSheetView.findViewById<TextView>(R.id.chargePointsNearMeLayout_textView_nearMe)
TransitionManager.beginDelayedTransition(bottomSheetView as ViewGroup?, Fade())
if (listOfChargePointsRecyclerView.visibility == View.GONE) {
arrow.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_reverse))
listOfChargePointsRecyclerView.visibility = View.VISIBLE
chargePointsNearMe.visibility = View.GONE
} else {
arrow.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate))
listOfChargePointsRecyclerView.visibility = View.GONE
chargePointsNearMe.visibility = View.VISIBLE
}
listOfChargePointsRecyclerView.layoutManager = LinearLayoutManager(this)
val refreshChargePoints = remoteChargePoints.refresh(lifecycleScope)
refreshChargePoints.invokeOnCompletion {
if (refreshChargePoints.isCancelled) {
return@invokeOnCompletion
}
val distanceToChargePoint = mutableListOf<Float>()
val chargerCount = mutableListOf<Int>()
Log.d("Distance", "${remoteChargePoints.value}")
remoteChargePoints.value.forEachIndexed { _, chargePoint ->
val dist = FloatArray(1)
try {
Location.distanceBetween(
chargePoint.location[0],
chargePoint.location[1],
currentLocation.latitude,
currentLocation.longitude,
dist
)
} catch (e: UninitializedPropertyAccessException) {
dist[0] = 0f
}
val distanceFloat = (dist[0] / 1000)
val roundedDistance = (distanceFloat * 100).roundToInt() / 100f
val count =
remoteChargers.value.count { it.chargePointID == chargePoint.chargePointID }
distanceToChargePoint.add(roundedDistance)
chargerCount.add(count)
}
val chargePointList = ArrayList(remoteChargePoints.value)
val indices = distanceToChargePoint.indices.sortedBy { distanceToChargePoint[it] }
val sortedDistanceToChargePoint = indices.map { distanceToChargePoint[it] }
val sortedChargerCount = indices.map { chargerCount[it] }.toMutableList()
val sortedChargePoints = indices.map { chargePointList[it] }
val sortedChargePointsList = ChargePoints()
sortedChargePointsList.addAll(sortedChargePoints)
val distanceAsString = mutableListOf<String>()
distanceAsString.addAll(sortedDistanceToChargePoint.map { it.toString() })
lifecycleScope.launch(Dispatchers.Main) {
listOfChargePointsRecyclerView.adapter = ChargePointListAdapter(
sortedChargePointsList,
this@MainActivity,
distanceAsString,
sortedChargerCount
)
}
}
}
private fun createKlarnaTransactionSession(
chargerId: Int
) {
val retrieveJob = currentRemoteTransaction.retrieve(lifecycleScope)
try {
retrieveJob.invokeOnCompletion {
if (retrieveJob.isCancelled) {
return@invokeOnCompletion
}
lifecycleScope.launch(Dispatchers.Main) {
val intent = Intent(this@MainActivity, KlarnaActivity::class.java)
intent.putExtra("ChargerId", chargerId)
intent.putExtra(
"klarna_consumer_token",
currentRemoteTransaction.klarnaConsumerToken
)
intent.putExtra("TransactionId", currentRemoteTransaction.transactionId)
startActivity(intent)
}
}
} catch (e: Exception) {
println("Error when retrieving")
}
}
private fun reserveCharger(chargerId: Int, chargerInputStatus: MaterialButton) {
val sharedPreferences = getSharedPreferences("loginPreference", Context.MODE_PRIVATE)
val transactionSession = TransactionSession(chargerId, "klarna")
val accessToken =
sharedPreferences.getString("accessToken", Context.MODE_PRIVATE.toString())
val createSessionJob =
currentRemoteTransaction.createSession(
lifecycleScope,
transactionSession,
accessToken!!
)
try {
createSessionJob.invokeOnCompletion {
if (createSessionJob.isCancelled) {
return@invokeOnCompletion
}
when (currentRemoteTransaction.status) {
"Accepted" -> {
createKlarnaTransactionSession(chargerId)
}
"Faulted" -> {
setChargerButtonStatus(chargerInputStatus, false, "Charger Faulted", 2)
}
"Occupied" -> {
setChargerButtonStatus(chargerInputStatus, false, "Charger Occupied", 2)
}
"Rejected" -> {
setChargerButtonStatus(chargerInputStatus, false, "Charger Rejected", 2)
}
"Unavailable" -> {
setChargerButtonStatus(chargerInputStatus, false, "Charger Unavailable", 2)
}
"Unauthorized" -> {
val intent = Intent(this, RegisterActivity::class.java)
startActivity(intent)
finish()
}
"OldToken" -> {
val intent = Intent(this, LoginActivity::class.java)
startActivity(intent)
finish()
}
else -> {
setChargerButtonStatus(
chargerInputStatus,
false,
"Charger Unknown status",
2
)
}
}
}
} catch (e: CancellationException) {
lifecycleScope.launch(Dispatchers.Main) {
setChargerButtonStatus(chargerInputStatus, false, "Could not reserve charger", 0)
}
Toast.makeText(
applicationContext,
"Could not reserve charger: " + e.message,
Toast.LENGTH_LONG
).show()
}
}
private fun displayChargerStatus(chargerId: Int, chargerInputStatus: MaterialButton) {
val remoteCharger = RemoteCharger(chargerId)
try {
val refreshJob = remoteCharger.refresh(lifecycleScope)
refreshJob.invokeOnCompletion {
if (refreshJob.isCancelled) {
return@invokeOnCompletion
}
val charger = remoteCharger.value
Log.d("validateConnection", "Connected to charger " + charger.connectorID)
lifecycleScope.launch(Dispatchers.Main) {
when (charger.status) {
"Available" -> {
showCheckout(true, charger.chargePointID, true, chargerId)
setChargerButtonStatus(chargerInputStatus, true, "Continue", 2)
}
"Faulted" -> {
setChargerButtonStatus(chargerInputStatus, false, "Charger Faulted", 0)
}
"Occupied" -> {
setChargerButtonStatus(chargerInputStatus, false, "Charger Occupied", 0)
}
"Rejected" -> {
setChargerButtonStatus(chargerInputStatus, false, "Charger Rejected", 0)
}
"Unavailable" -> {
setChargerButtonStatus(
chargerInputStatus,
false,
"Charger Unavailable",
0
)
}
"Charging" -> {
setChargerButtonStatus(
chargerInputStatus,
false,
"Charger is occupied",
0
)
}
"Reserved" -> {
setChargerButtonStatus(
chargerInputStatus,
false,
"Charger is reserved",
0
)
}
else -> {
setChargerButtonStatus(
chargerInputStatus,
false,
"Charger is " + charger.status,
2
)
}
}
}
}
} catch (e: CancellationException) {
lifecycleScope.launch(Dispatchers.Main) {
setChargerButtonStatus(chargerInputStatus, false, e.message!!, 2)
}
}
}
private fun setChargerButtonStatus(
chargerInputStatus: MaterialButton,
active: Boolean,
text: String,
color: Int
) {
chargerInputStatus.isClickable = active
chargerInputStatus.text = text
when (color) {
0 -> {
chargerInputStatus.setBackgroundColor(getColor(R.color.red))
chargerInputStatus.setTextColor(getColor(R.color.white))
}
1 -> {
chargerInputStatus.setBackgroundColor(getColor(R.color.green))
chargerInputStatus.setTextColor(getColor(R.color.white))
}
2 -> {
chargerInputStatus.setBackgroundColor(getColor(R.color.light_grey))
chargerInputStatus.setTextColor(getColor(R.color.black))
}
3 -> {
chargerInputStatus.setBackgroundColor(getColor(R.color.dark_grey))
chargerInputStatus.setTextColor(getColor(R.color.white))
}
}
}
fun validateChargerId(chargerId: String): Boolean {
if (chargerId.length != 6) {
return false
}
if (chargerId.count { it.isDigit() } != 6) {
return false
}
return true
}
private fun checkPendingTransaction() {
// TODO Fix fetching transaction ID smartly
val sharedPreferences = getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE)
val transactionId = sharedPreferences.getInt("TransactionId", -1)
if (transactionId == -1) {
Log.d("StartVerify", "No active transaction")
return
}
currentRemoteTransaction.transactionId = transactionId
val refreshJob = currentRemoteTransaction.refresh(lifecycleScope)
refreshJob.invokeOnCompletion {
if (refreshJob.isCancelled) {
Log.d("StartVerify", "Refresh fail")
return@invokeOnCompletion
}
lifecycleScope.launch(Dispatchers.Main) {
try {
Log.d("StartVerify", "Set up charger")
setupChargingInProgressDialog()
} catch (e: Exception) {
Log.d("CheckTransaction", "Found an errors")
Toast.makeText(
applicationContext,
e.message + " : " + e.cause,
Toast.LENGTH_LONG
).show()
}
}
}
}
private fun showCheckout(
bool: Boolean,
chargePointId: Int,
showPayment: Boolean,
chargerId: Int
) {
val checkoutLayout =
chargerInputDialog.findViewById<ConstraintLayout>(R.id.charger_checkout_layout)
val chargersNearMeLayout =
chargerInputDialog.findViewById<ConstraintLayout>(R.id.chargePoints_near_me_layout)
val chargerInput =
chargerInputDialog.findViewById<EditText>(R.id.chargerInputLayout_pinView_chargerInput)
val chargerInputStatus =
chargerInputDialog.findViewById<MaterialButton>(
R.id.chargerInputLayout_textView_chargerStatus
)
val chargerInputView =
chargerInputDialog.findViewById<ConstraintLayout>(R.id.chargerInputLayout)
val chargerLocationText =
chargerInputDialog.findViewById<TextView>(R.id.checkoutLayout_textView_currentLocation)
val paymentText =
chargerInputDialog.findViewById<TextView>(R.id.checkoutLayout_textView_payment)
val klarnaButton =
chargerInputDialog.findViewById<ImageButton>(R.id.checkoutLayout_button_klarna)
TransitionManager.beginDelayedTransition(chargerInputView as ViewGroup?, ChangeBounds())
if (bool) {
chargersNearMeLayout?.visibility = View.GONE
checkoutLayout?.visibility = View.VISIBLE
if (showPayment) {
klarnaButton?.background =
AppCompatResources.getDrawable(this, R.drawable.rounded_background)
klarnaButton?.visibility = View.VISIBLE
paymentText?.visibility = View.VISIBLE
chargerInput?.isEnabled = false
chargerInputStatus?.isEnabled = false
klarnaButton?.setOnClickListener {
klarnaButton.background =
AppCompatResources.getDrawable(this, R.drawable.rounded_background_selected)
chargerInputStatus?.isEnabled = true
if (chargerInputStatus != null) {
setChargerButtonStatus(chargerInputStatus, true, "Continue", 1)
}
// reserveCharger(chargerId, chargerInputStatus!!)
}
chargerInputStatus?.setOnClickListener {
reserveCharger(chargerId, chargerInputStatus)
}
} else {
klarnaButton?.visibility = View.GONE
paymentText?.visibility = View.GONE
chargerInput?.isEnabled = true
}
try {
val chargerWithChargePointId =
remoteChargePoints.value.first { it.chargePointID == chargePointId }
chargerLocationText?.text = chargerWithChargePointId.name
} catch (e: NoSuchElementException) {
Log.d(
"remoteChargePoints",
"couldn't find a charger with chargePointID $chargePointId"
)
}
if (chargerInputView != null) {
displayChargerList(chargerInputView, chargePointId)
}
} else {
chargerInput?.isEnabled = true
chargersNearMeLayout?.visibility = View.VISIBLE
checkoutLayout?.visibility = View.GONE
chargerInput?.text?.clear()
setChargerButtonStatus(
chargerInputStatus!!,
false,
getString(R.string.charger_status_enter_code),
3
)
}
}
override fun finish() {
super.finish()
remoteChargersRefresher.stop()
}
}