/
DiseasesFragment.kt
381 lines (364 loc) · 15.6 KB
/
DiseasesFragment.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
/*
* Copyright © 2020 - present | Handwashing reminder by Javinator9889
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*
* Created by Javinator9889 on 12/04/20 - Handwashing reminder.
*/
package com.javinator9889.handwashingreminder.activities.views.fragments.diseases
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.LinearLayout
import androidx.annotation.StringRes
import androidx.core.app.ActivityCompat
import androidx.emoji.text.EmojiCompat
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.observe
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.github.mikephil.charting.data.BarData
import com.github.mikephil.charting.data.BarDataSet
import com.github.mikephil.charting.formatter.ValueFormatter
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_COLLAPSED
import com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_EXPANDED
import com.google.android.material.textview.MaterialTextView
import com.javinator9889.handwashingreminder.R
import com.javinator9889.handwashingreminder.activities.base.BaseFragmentView
import com.javinator9889.handwashingreminder.activities.base.LayoutVisibilityChange
import com.javinator9889.handwashingreminder.activities.views.fragments.diseases.adapter.Ads
import com.javinator9889.handwashingreminder.activities.views.fragments.diseases.adapter.Disease
import com.javinator9889.handwashingreminder.activities.views.viewmodels.DiseaseInformationViewModel
import com.javinator9889.handwashingreminder.activities.views.viewmodels.SavedViewModelFactory
import com.javinator9889.handwashingreminder.data.ParsedHTMLText
import com.javinator9889.handwashingreminder.data.room.entities.Handwashing
import com.javinator9889.handwashingreminder.data.viewmodels.HandwashingViewModel
import com.javinator9889.handwashingreminder.emoji.EmojiLoader
import com.javinator9889.handwashingreminder.utils.calendar.CalendarUtils
import com.javinator9889.handwashingreminder.utils.toBarEntry
import com.mikepenz.fastadapter.FastAdapter
import com.mikepenz.fastadapter.GenericItem
import com.mikepenz.fastadapter.adapters.ItemAdapter
import com.mikepenz.fastadapter.listeners.ClickEventHook
import kotlinx.android.synthetic.main.handwash_count.*
import kotlinx.android.synthetic.main.handwash_count.view.*
import kotlinx.android.synthetic.main.loading_recycler_view.*
import kotlinx.android.synthetic.main.loading_recycler_view.view.*
import kotlinx.android.synthetic.main.main_disease_view.view.*
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.launch
import timber.log.Timber
class DiseasesFragment : BaseFragmentView(), LayoutVisibilityChange, View.OnClickListener {
override val layoutId: Int = R.layout.main_disease_view
private lateinit var parsedHTMLTexts: List<ParsedHTMLText>
private lateinit var fastAdapter: FastAdapter<GenericItem>
private lateinit var emojiLoader: Deferred<EmojiCompat>
private lateinit var behavior: BottomSheetBehavior<LinearLayout>
private val upperAdsAdapter: ItemAdapter<Ads> = ItemAdapter()
private val lowerAdsAdapter: ItemAdapter<Ads> = ItemAdapter()
private val diseasesAdapter: ItemAdapter<Disease> = ItemAdapter()
private val informationViewModel: DiseaseInformationViewModel by viewModels {
SavedViewModelFactory(DiseaseInformationViewModel.Factory, this)
}
private val handwashingViewModel: HandwashingViewModel by activityViewModels()
private var dataSet: BarDataSet? = null
init {
lifecycleScope.launchWhenStarted {
loading.visibility = View.VISIBLE
countLoader.visibility = View.VISIBLE
informationViewModel.parsedHTMLText.observe(viewLifecycleOwner) {
if (it.isEmpty())
return@observe
parsedHTMLTexts = it
it.forEachIndexed { i, parsedText ->
val animation =
if (i % 2 == 0) R.raw.virus_red
else R.raw.virus_loader
val layoutId =
if (i % 2 == 0) R.layout.disease_card_layout
else R.layout.disease_card_alt_layout
val disease = Disease(animation, parsedText, layoutId, i)
if (diseasesAdapter.getAdapterPosition(disease) == -1)
diseasesAdapter.add(disease)
}
loading.visibility = View.INVISIBLE
container.visibility = View.VISIBLE
}
handwashingViewModel.allData.observe(viewLifecycleOwner) {
lifecycleScope.launch {
dataSet?.let { set ->
Timber.d("Adding new items to dataSet")
set.clear()
for (entry in it.toBarEntry()) {
set.addEntry(entry)
// countChart.notifyDataSetChanged()
}
} ?: with(BarDataSet(it.toBarEntry(), "")) {
Timber.d("dataSet not created so instantiating it")
valueFormatter = IntFormatter()
dataSet = this
// countChart.data.addDataSet(this)
// countChart.notifyDataSetChanged()
}
countChart.data = BarData(dataSet)
countChart.notifyDataSetChanged()
// countChart.data.notifyDataChanged()
// countChart.minOffset = 0F
// countChart.setExtraOffsets(4F, 4F, 4F, 4F)
// countChart.setViewPortOffsets(0F, 4F, 0F, 0F)
// countChart.data = BarData(dataSet)
// countChart.notifyDataSetChanged()
// countChart.axisLeft.axisMinimum = 0F
// countChart.data.notifyDataChanged()
countChart.fitScreen()
countChart.moveViewToX(0F)
countChart.invalidate()
val todayAmount =
handwashingViewModel.getAsync(CalendarUtils.today.time)
val weeklyAmount =
handwashingViewModel.getWeeklyCountAsync()
val monthlyAmount =
handwashingViewModel.getMonthlyCountAsync()
setCountText(
countDailyTextView,
R.string.today_washed,
todayAmount.await()?.amount ?: 0
)
setCountText(
countWeeklyTextView,
R.string.week_washed,
weeklyAmount.await()
)
setCountText(
countMonthlyTextView,
R.string.month_washed,
monthlyAmount.await()
)
countLoader.visibility = View.INVISIBLE
scrollView.visibility = View.VISIBLE
}
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
emojiLoader = EmojiLoader.loadAsync(view.context)
val adapters = listOf(upperAdsAdapter, diseasesAdapter, lowerAdsAdapter)
fastAdapter = FastAdapter.with(adapters)
val rvManager = LinearLayoutManager(context)
with(view.container) {
layoutManager = rvManager
adapter = fastAdapter
}
fastAdapter.addEventHook(DiseaseClickEventHook())
fastAdapter.withSavedInstanceState(savedInstanceState)
behavior = BottomSheetBehavior.from(view.contentLayout)
behavior.addBottomSheetCallback(BottomSheetStateCallback())
view.countChart.setDrawGridBackground(false)
view.countChart.axisLeft.apply {
setDrawGridLines(false)
valueFormatter = IntFormatter()
isGranularityEnabled = true
granularity = 1F
axisMinimum = 0F
// spaceMax = .01F
}
view.countChart.axisRight.apply {
setDrawGridLines(false)
valueFormatter = IntFormatter()
isGranularityEnabled = true
granularity = 1F
axisMinimum = 0F
// spaceMax = .01F
}
view.countChart.xAxis.apply {
setDrawGridLines(false)
valueFormatter = IntFormatter()
isGranularityEnabled = true
granularity = 1F
axisMaximum = 0F
}
view.countChart.setVisibleXRangeMaximum(7F)
view.countChart.isAutoScaleMinMaxEnabled = true
view.countChart.legend.isEnabled = false
view.countChart.description.isEnabled = false
// view.countChart.extraTopOffset = 16F
// view.countChart.extraTopOffset = dpToPx(4F)
view.countChart.invalidate()
view.countUpButton.setOnClickListener(this)
view.countDownButton.setOnClickListener(this)
/*view.countUpButton.setOnClickListener {
lifecycleScope.launch {
val createdItem =
handwashingViewModel.getAsync(CalendarUtils.today.time)
.await()
if (createdItem == null)
handwashingViewModel.create(
Handwashing(
CalendarUtils.today.time,
0
)
)
handwashingViewModel.increment(CalendarUtils.today.time)
leaves.visibility = View.VISIBLE
if (!leaves.isAnimating)
leaves.playAnimation()
}
}
view.countDownButton.setOnClickListener {
lifecycleScope.launch {
val createdItem =
handwashingViewModel.getAsync(CalendarUtils.today.time)
.await()
if (createdItem == null)
handwashingViewModel.create(
Handwashing(
CalendarUtils.today.time,
0
)
)
handwashingViewModel.decrement(CalendarUtils.today.time)
}
}*/
lifecycleScope.launch {
val countUpText = getText(R.string.add_another)
val countDownText = getText(R.string.reduce_count)
val emojiCompat = emojiLoader.await()
try {
countUpButton.text = emojiCompat.process(countUpText)
countDownButton.text = emojiCompat.process(countDownText)
} catch (_: IllegalStateException) {
countUpButton.text = countUpText
countDownButton.text = countDownText
}
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
fastAdapter.saveInstanceState(outState)
}
fun onBackPressed() {
if (::behavior.isInitialized) {
if (behavior.state == STATE_EXPANDED) {
behavior.state = STATE_COLLAPSED
return
}
}
try {
container.adapter = null
diseasesAdapter.clear()
} catch (e: Exception) {
Timber.w(e, "Exception when calling 'onBackPressed'")
} finally {
onDestroy()
}
}
override fun onVisibilityChanged(visibility: Int) {
/*if (visibility == View.VISIBLE)
lifecycleScope.launchWhenCreated { informationViewModel.parseHtml() }*/
}
override fun onClick(v: View?) {
when (v) {
countUpButton -> lifecycleScope.launch {
val createdItem =
handwashingViewModel.getAsync(CalendarUtils.today.time)
.await()
if (createdItem == null)
handwashingViewModel.create(
Handwashing(
CalendarUtils.today.time,
0
)
)
handwashingViewModel.increment(CalendarUtils.today.time)
leaves.visibility = View.VISIBLE
if (!leaves.isAnimating)
leaves.playAnimation()
}
countDownButton -> lifecycleScope.launch {
val createdItem =
handwashingViewModel.getAsync(CalendarUtils.today.time)
.await()
if (createdItem == null)
handwashingViewModel.create(
Handwashing(
CalendarUtils.today.time,
0
)
)
handwashingViewModel.decrement(CalendarUtils.today.time)
}
}
}
private suspend fun setCountText(
view: MaterialTextView,
@StringRes id: Int,
times: Int
) {
val emojiCompat = emojiLoader.await()
val text = getString(
id,
resources.getQuantityString(R.plurals.times, times, times)
)
view.text = try {
emojiCompat.process(text)
} catch (_: IllegalStateException) {
text
}
}
private inner class DiseaseClickEventHook : ClickEventHook<Disease>() {
override fun onBind(viewHolder: RecyclerView.ViewHolder) =
if (viewHolder is Disease.ViewHolder) viewHolder.cardContainer
else null
override fun onClick(
v: View,
position: Int,
fastAdapter: FastAdapter<Disease>,
item: Disease
) {
val parsedHTMLText = item.information
val animId = item.animation
val intent = Intent(
requireContext(),
DiseaseExpandedView::class.java
)
intent.putExtra(ARG_ANIMATION, animId)
intent.putExtra(ARG_PARSED_TEXT, parsedHTMLText)
ActivityCompat.startActivity(
requireContext(),
intent,
null
)
}
}
private inner class BottomSheetStateCallback :
BottomSheetBehavior.BottomSheetCallback() {
override fun onStateChanged(bottomSheet: View, newState: Int) {
if (newState == STATE_EXPANDED) {
if (upperAdsAdapter.adapterItemCount == 0)
upperAdsAdapter.add(Ads())
if (lowerAdsAdapter.adapterItemCount == 0)
lowerAdsAdapter.add(Ads())
informationViewModel.parseHtml()
}
}
override fun onSlide(bottomSheet: View, slideOffset: Float) {}
}
private inner class IntFormatter : ValueFormatter() {
override fun getFormattedValue(value: Float) = value.toInt().toString()
}
}