4 Commits

6 changed files with 612 additions and 102 deletions

View File

@@ -60,5 +60,7 @@ dependencies {
androidTestImplementation(libs.androidx.ui.test.junit4) androidTestImplementation(libs.androidx.ui.test.junit4)
debugImplementation(libs.androidx.ui.tooling) debugImplementation(libs.androidx.ui.tooling)
debugImplementation(libs.androidx.ui.test.manifest) debugImplementation(libs.androidx.ui.test.manifest)
implementation(libs.mpandroidchart.vv310) implementation("com.github.PhilJay:MPAndroidChart:v3.1.0")
// implementation(libs.mpandroidchart)
//implementation project(':MPChartLib')
} }

View File

@@ -51,8 +51,6 @@ class MainActivity : AppCompatActivity() {
const val TAG = "MainActivity" const val TAG = "MainActivity"
const val UPDATE_EVERY_SECS: Long = 30 const val UPDATE_EVERY_SECS: Long = 30
const val DEBUG_CHECK_LOGBOOK_CONSISTENCY = false const val DEBUG_CHECK_LOGBOOK_CONSISTENCY = false
// list of all events
var allEvents = arrayListOf<LunaEvent>()
} }
var logbook: Logbook? = null var logbook: Logbook? = null
@@ -148,8 +146,7 @@ class MainActivity : AppCompatActivity() {
if (logbook == null) if (logbook == null)
Log.w(TAG, "showLogbook(): logbook is null!") Log.w(TAG, "showLogbook(): logbook is null!")
allEvents = logbook?.logs ?: arrayListOf() setListAdapter(logbook?.logs ?: arrayListOf())
setListAdapter(allEvents)
} }
override fun onStart() { override fun onStart() {
@@ -196,6 +193,10 @@ class MainActivity : AppCompatActivity() {
super.onStop() super.onStop()
} }
fun getAllEvents(): ArrayList<LunaEvent> {
return logbook?.logs ?: arrayListOf()
}
fun addBabyBottleEvent(event: LunaEvent) { fun addBabyBottleEvent(event: LunaEvent) {
setToPreviousQuantity(event) setToPreviousQuantity(event)
askBabyBottleContent(event, true) { askBabyBottleContent(event, true) {
@@ -363,7 +364,7 @@ class MainActivity : AppCompatActivity() {
} }
fun saveEvent(event: LunaEvent) { fun saveEvent(event: LunaEvent) {
if (!allEvents.contains(event)) { if (!getAllEvents().contains(event)) {
// new event // new event
logEvent(event) logEvent(event)
} }
@@ -557,7 +558,7 @@ class MainActivity : AppCompatActivity() {
val nextTextView = dialogView.findViewById<TextView>(R.id.notes_template_next) val nextTextView = dialogView.findViewById<TextView>(R.id.notes_template_next)
val prevTextView = dialogView.findViewById<TextView>(R.id.notes_template_prev) val prevTextView = dialogView.findViewById<TextView>(R.id.notes_template_prev)
val templates = allEvents.filter { it.type == event.type }.distinctBy { it.notes }.sortedBy { it.time } val templates = getAllEvents().filter { it.type == event.type }.distinctBy { it.notes.trim() }.sortedBy { it.time }
fun updateContent(current: LunaEvent) { fun updateContent(current: LunaEvent) {
val prevEvent = getPreviousSameEvent(current, templates) val prevEvent = getPreviousSameEvent(current, templates)
@@ -612,7 +613,7 @@ class MainActivity : AppCompatActivity() {
updateContent(event) updateContent(event)
d.setPositiveButton(android.R.string.ok) { dialogInterface, i -> d.setPositiveButton(android.R.string.ok) { dialogInterface, i ->
val notes = notesET.text.toString().trim() val notes = notesET.text.toString()
if (useQuantity) { if (useQuantity) {
val quantity = qtyET.text.toString().toIntOrNull() val quantity = qtyET.text.toString().toIntOrNull()
@@ -663,7 +664,7 @@ class MainActivity : AppCompatActivity() {
} }
fun setToPreviousQuantity(event: LunaEvent) { fun setToPreviousQuantity(event: LunaEvent) {
val prev = getPreviousSameEvent(event, allEvents) val prev = getPreviousSameEvent(event, getAllEvents())
if (prev != null) { if (prev != null) {
event.quantity = prev.quantity event.quantity = prev.quantity
} }
@@ -808,6 +809,8 @@ class MainActivity : AppCompatActivity() {
signatureTextEdit.visibility = View.VISIBLE signatureTextEdit.visibility = View.VISIBLE
} }
val allEvents = getAllEvents()
// create link to prevent event of the same type // create link to prevent event of the same type
val previousTextView = dialogView.findViewById<TextView>(R.id.dialog_event_previous) val previousTextView = dialogView.findViewById<TextView>(R.id.dialog_event_previous)
val previousEvent = getPreviousSameEvent(event, allEvents) val previousEvent = getPreviousSameEvent(event, allEvents)

View File

@@ -16,7 +16,18 @@ import com.github.mikephil.charting.data.BarDataSet
import com.github.mikephil.charting.data.BarEntry import com.github.mikephil.charting.data.BarEntry
import com.github.mikephil.charting.formatter.ValueFormatter import com.github.mikephil.charting.formatter.ValueFormatter
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet import com.github.mikephil.charting.interfaces.datasets.IBarDataSet
import com.thegrizzlylabs.sardineandroid.impl.SardineException
import it.danieleverducci.lunatracker.MainActivity.Companion.TAG
import it.danieleverducci.lunatracker.entities.Logbook
import it.danieleverducci.lunatracker.entities.LunaEvent import it.danieleverducci.lunatracker.entities.LunaEvent
import it.danieleverducci.lunatracker.repository.FileLogbookRepository
import it.danieleverducci.lunatracker.repository.LocalSettingsRepository
import it.danieleverducci.lunatracker.repository.LogbookListObtainedListener
import it.danieleverducci.lunatracker.repository.LogbookLoadedListener
import it.danieleverducci.lunatracker.repository.LogbookRepository
import it.danieleverducci.lunatracker.repository.WebDAVLogbookRepository
import okio.IOException
import org.json.JSONException
import utils.DateUtils.Companion.formatTimeDuration import utils.DateUtils.Companion.formatTimeDuration
import utils.NumericUtils import utils.NumericUtils
import java.util.Calendar import java.util.Calendar
@@ -24,24 +35,222 @@ import java.util.Date
import kotlin.math.max import kotlin.math.max
import kotlin.math.min import kotlin.math.min
class StatisticsActivity : AppCompatActivity() { abstract class LogbookBase: AppCompatActivity() {
var logbook: Logbook? = null
var logbookName: String? = null
lateinit var logbookRepo: LogbookRepository
fun initLogbookBase() {
Log.d(TAG, "LogbookBase init")
val settingsRepository = LocalSettingsRepository(this)
if (settingsRepository.loadDataRepository() == LocalSettingsRepository.DATA_REPO.WEBDAV) {
val webDavCredentials = settingsRepository.loadWebdavCredentials()
if (webDavCredentials == null) {
throw IllegalStateException("Corrupted local settings: repo is webdav, but no webdav login data saved")
}
logbookRepo = WebDAVLogbookRepository(
webDavCredentials[0],
webDavCredentials[1],
webDavCredentials[2]
)
} else {
logbookRepo = FileLogbookRepository()
}
if (logbook != null) {
// Already running: reload data for currently selected logbook
loadLogbook(logbook!!.name)
} else {
// First start: load logbook list
loadLogbookList()
}
}
abstract fun onLogbookReady()
fun loadLogbook(name: String) {
//if (savingEvent)
// return
// Reset time counter
//handler.removeCallbacks(updateListRunnable)
//handler.postDelayed(updateListRunnable, UPDATE_EVERY_SECS*1000)
// Load data
//setLoading(true)
logbookRepo?.loadLogbook(this, name, object: LogbookLoadedListener{
override fun onLogbookLoaded(lb: Logbook) {
runOnUiThread({
Log.d("StatisticsActivity", "logbook loaded!")
//setLoading(false)
//findViewById<View>(R.id.no_connection_screen).visibility = View.GONE
logbook = lb
//val events = logbook?.logs ?: arrayListOf()
onLogbookReady()//updateGraph() //events) // showLogbook()
/*
if (DEBUG_CHECK_LOGBOOK_CONSISTENCY) {
for (e in logbook?.logs ?: listOf()) {
val em = e.getTypeEmoji(this@MainActivity)
if (em == getString(R.string.event_unknown_type)) {
Log.e(TAG, "UNKNOWN: ${e.type}")
}
}
}
*/
})
}
override fun onIOError(error: IOException) {
runOnUiThread({
//setLoading(false)
onRepoError(getString(R.string.settings_network_error) + error.toString())
})
}
override fun onWebDAVError(error: SardineException) {
runOnUiThread({
//setLoading(false)
onRepoError(
if(error.toString().contains("401")) {
getString(R.string.settings_webdav_error_denied)
} else if(error.toString().contains("503")) {
getString(R.string.settings_webdav_error_server_offline)
} else {
getString(R.string.settings_webdav_error_generic) + error.toString()
}
)
})
}
override fun onJSONError(error: JSONException) {
runOnUiThread({
//setLoading(false)
onRepoError(getString(R.string.settings_json_error) + error.toString())
})
}
override fun onError(error: Exception) {
runOnUiThread({
//setLoading(false)
onRepoError(getString(R.string.settings_generic_error) + error.toString())
})
}
})
}
fun loadLogbookList() {
//setLoading(true)
logbookRepo?.listLogbooks(this, object: LogbookListObtainedListener {
override fun onLogbookListObtained(logbooksNames: ArrayList<String>) {
if (logbooksNames.isNotEmpty()) {
loadLogbook(logbooksNames[0])
}
/*
runOnUiThread({
if (logbooksNames.isEmpty()) {
// First run, no logbook: create one
//showAddLogbookDialog(false)
return@runOnUiThread
}
// Show logbooks dropdown
val spinner = findViewById<Spinner>(R.id.logbooks_spinner)
val sAdapter = ArrayAdapter<String>(this@StatisticsActivity, android.R.layout.simple_spinner_item)
sAdapter.setDropDownViewResource(R.layout.row_logbook_spinner)
for (ln in logbooksNames) {
sAdapter.add(
ln.ifEmpty { getString(R.string.default_logbook_name) }
)
}
spinner.adapter = sAdapter
spinner.onItemSelectedListener = object: AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
// Changed logbook: empty list
setListAdapter(arrayListOf())
// Load logbook
loadLogbook(logbooksNames.get(position))
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
}
})
*/
}
override fun onIOError(error: IOException) {
Log.e(TAG, "Unable to load logbooks list (IOError): $error")
runOnUiThread({
//setLoading(false)
onRepoError(getString(R.string.settings_network_error) + error.toString())
})
}
override fun onWebDAVError(error: SardineException) {
Log.e(TAG, "Unable to load logbooks list (SardineException): $error")
runOnUiThread({
//setLoading(false)
onRepoError(
if(error.toString().contains("401")) {
getString(R.string.settings_webdav_error_denied)
} else if(error.toString().contains("503")) {
getString(R.string.settings_webdav_error_server_offline)
} else {
getString(R.string.settings_webdav_error_generic) + error.toString()
}
)
})
}
override fun onError(error: Exception) {
Log.e(TAG, "Unable to load logbooks list: $error")
runOnUiThread({
//setLoading(false)
onRepoError(getString(R.string.settings_generic_error) + error.toString())
})
}
})
}
fun onRepoError(message: String) {
runOnUiThread({
//setLoading(false)
//findViewById<View>(R.id.no_connection_screen).visibility = View.VISIBLE
//findViewById<TextView>(R.id.no_connection_screen_message).text = message
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
})
}
fun getAllEvents(): ArrayList<LunaEvent> {
return logbook?.logs ?: arrayListOf()
}
}
open class StatisticsActivity : LogbookBase() {
lateinit var barChart: BarChart lateinit var barChart: BarChart
lateinit var noDataTextView: TextView lateinit var noDataTextView: TextView
lateinit var eventTypeSelection: Spinner lateinit var eventTypeSelection: Spinner
lateinit var dataTypeSelection: Spinner lateinit var dataTypeSelection: Spinner
lateinit var timeRangeSelection: Spinner lateinit var timeRangeSelection: Spinner
// default selection
var eventTypeSelectionValue = "BOTTLE" var eventTypeSelectionValue = "BOTTLE"
var dataTypeSelectionValue = "AMOUNT" var dataTypeSelectionValue = "AMOUNT"
var timeRangeSelectionValue = "DAY" var timeRangeSelectionValue = "DAY"
override fun onLogbookReady() {
updateGraph()
}
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
setContentView(R.layout.activity_statistics) setContentView(R.layout.activity_statistics)
val logbookName = intent.getStringExtra("LOOGBOOK_NAME") logbookName = intent.getStringExtra("LOOGBOOK_NAME")
if (logbookName == null) { if (logbookName == null) {
finish() finish()
return return
@@ -52,19 +261,75 @@ class StatisticsActivity : AppCompatActivity() {
barChart = findViewById(R.id.bar_chart) barChart = findViewById(R.id.bar_chart)
barChart.setBackgroundColor(Color.WHITE) barChart.setBackgroundColor(Color.WHITE)
barChart.description.text = "$logbookName" barChart.description.text = "$logbookName"
barChart.setDrawValueAboveBar(false) //barChart.description.isEnabled = false
barChart.axisLeft.setAxisMinimum(0F) barChart.axisLeft.setAxisMinimum(0F)
barChart.axisLeft.setDrawGridLines(false)
/*
barChart.setFitBars(true)
barChart.setMaxVisibleValueCount(30)
barChart.axisLeft.setDrawLabels(false) barChart.axisLeft.setDrawLabels(false)
barChart.axisRight.setDrawLabels(true)
barChart.axisRight.setDrawGridLines(false)
barChart.axisRight.setDrawLabels(false)
barChart.xAxis.setDrawGridLines(true)
barChart.xAxis.setDrawLabels(true) barChart.xAxis.setDrawLabels(true)
barChart.xAxis.setDrawAxisLine(false) barChart.legend.setEnabled(false)
barChart.setDrawValueAboveBar(true)
//barChart.setVisibleXRangeMaximum(30f)
*/
/*
val seekBar = findViewById<SeekBar>(R.id.seekBar);
seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(
seekBar: SeekBar?,
progress: Int,
fromUser: Boolean
) {
//tvX.setText(java.lang.String.valueOf(seekBar.getProgress()))
//tvY.setText(java.lang.String.valueOf(seekBarY.getProgress()))
//setData(seekBarX.getProgress(), seekBarY.getProgress())
barChart.setFitBars(true)
barChart.invalidate()
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {}
override fun onStopTrackingTouch(seekBar: SeekBar?) {}
})
*/
/*
// if more than 60 entries are displayed in the barChart, no values will be
// drawn
//barChart.setMaxVisibleValueCount(60)
barChart.setScaleMinima(2f, 1f)
// scaling can now only be done on x- and y-axis separately
barChart.setPinchZoom(true)
// draw shadows for each bar that show the maximum value
barChart.setDrawBarShadow(true)
barChart.setDrawGridBackground(true)
val xl = barChart.getXAxis()
xl.position = XAxisPosition.BOTTOM
//xl.setTypeface(tfLight)
xl.setDrawAxisLine(true)
xl.setDrawGridLines(false)
//xl.setGranularity(10f)
// yl.setInverted(true);
val yr = barChart.axisRight
//yr.setTypeface(tfLight)
yr.setDrawAxisLine(true)
yr.setDrawGridLines(false)
yr.setAxisMinimum(0f) // this replaces setStartAtZero(true)
// yr.setInverted(true);
barChart.setFitBars(true)
barChart.animateY(500)
*/
eventTypeSelection = findViewById(R.id.type_selection) eventTypeSelection = findViewById(R.id.type_selection)
dataTypeSelection = findViewById(R.id.data_selection) dataTypeSelection = findViewById(R.id.data_selection)
timeRangeSelection = findViewById(R.id.time_selection) timeRangeSelection = findViewById(R.id.time_selection)
@@ -77,7 +342,7 @@ class StatisticsActivity : AppCompatActivity() {
override fun call(newValue: String?) { override fun call(newValue: String?) {
if (newValue != null) { if (newValue != null) {
eventTypeSelectionValue = newValue eventTypeSelectionValue = newValue
//Log.d("event", "new value: $newValue") Log.d("event", "new value: $newValue")
updateGraph() updateGraph()
} }
} }
@@ -92,7 +357,7 @@ class StatisticsActivity : AppCompatActivity() {
override fun call(newValue: String?) { override fun call(newValue: String?) {
if (newValue != null) { if (newValue != null) {
dataTypeSelectionValue = newValue dataTypeSelectionValue = newValue
//Log.d("event", "new value: $newValue") Log.d("event", "new value: $newValue")
updateGraph() updateGraph()
} }
} }
@@ -107,51 +372,90 @@ class StatisticsActivity : AppCompatActivity() {
override fun call(newValue: String?) { override fun call(newValue: String?) {
if (newValue != null) { if (newValue != null) {
timeRangeSelectionValue = newValue timeRangeSelectionValue = newValue
//Log.d("event", "new value: $newValue") Log.d("event", "new value: $newValue")
updateGraph() updateGraph()
} }
} }
} }
) )
updateGraph() initLogbookBase()
} }
/*
fun massageData(): Triple<Float, Float, Float>
Triple(, ,)
)
*/
fun updateGraph() { fun updateGraph() {
//eventTypeSelectionValue = "SLEEP"
//dataTypeSelectionValue = "AMOUNT"
//timeRangeSelectionValue = "DAY"
//val allEvents = getAllEvents()
//Log.d("StatisticsActivity", "updateGraph: allEvents: ${allEvents.size}")
Log.d("StatisticsActivity", "eventTypeSelectionValue: $eventTypeSelectionValue, dataTypeSelectionValue: $dataTypeSelectionValue, timeRange: $timeRangeSelectionValue")
// for quantity
fun formatEventValue(value: Float): String {
return when (eventTypeSelectionValue) {
"BOTTLE" -> {
NumericUtils(applicationContext).formatEventQuantity(LunaEvent.TYPE_BABY_BOTTLE, value.toInt())
}
"SLEEP" -> {
NumericUtils(applicationContext).formatEventQuantity(LunaEvent.TYPE_SLEEP, value.toInt())
}
else -> {
Log.e(TAG, "invalid dataTypeSelectionValue: $dataTypeSelectionValue")
"${value.toInt()}"
}
}
}
val eventType = when (eventTypeSelectionValue) { val eventType = when (eventTypeSelectionValue) {
"BOTTLE" -> LunaEvent.TYPE_BABY_BOTTLE "BOTTLE" -> LunaEvent.TYPE_BABY_BOTTLE
"SLEEP" -> LunaEvent.TYPE_SLEEP "SLEEP" -> LunaEvent.TYPE_SLEEP
else -> { else -> {
Log.e(TAG, "unhandled eventTypeSelectionValue: $eventTypeSelectionValue") Log.e(TAG, "Invalid eventTypeSelectionValue: $eventTypeSelectionValue")
return return
} }
} }
val allEvents = MainActivity.allEvents.filter { it.type == eventType }.sortedBy { it.time } val allEvents = getAllEvents().filter { it.type == eventType }.sortedBy { it.time }
Log.d("StatisticsActivity", "events: ${allEvents.size}")
val values = ArrayList<BarEntry>() val values = ArrayList<BarEntry>()
val labels = ArrayList<String>() val labels = ArrayList<String>()
val unixToSpan = when (timeRangeSelectionValue) { val unixToSpan: ((Long) -> Int) = { unix ->
"DAY" -> { unix: Long -> unixToDays(unix) } when (timeRangeSelectionValue) {
"WEEK" -> { unix: Long -> unixToWeeks(unix) } "DAY" -> unixToDays(unix)
"MONTH" -> { unix: Long -> unixToMonths(unix) } "WEEK" -> unixToWeeks(unix)
"MONTH" -> unixToMonths(unix)
else -> { else -> {
Log.e(TAG, "Invalid timeRangeSelectionValue: $timeRangeSelectionValue") Log.e(TAG, "Invalid timeRangeSelectionValue: $timeRangeSelectionValue")
return 0
}
} }
} }
val spanToUnix = when (timeRangeSelectionValue) { val spanToUnix: ((Int) -> Long) = { span ->
"DAY" -> { span: Int -> daysToUnix(span) } when (timeRangeSelectionValue) {
"WEEK" -> { span: Int -> weeksToUnix(span) } "DAY" -> daysToUnix(span)
"MONTH" -> { span: Int -> monthsToUnix(span) } "WEEK" -> weeksToUnix(span)
"MONTH" -> monthToUnix(span)
else -> { else -> {
Log.e(TAG, "Invalid timeRangeSelectionValue: $timeRangeSelectionValue") Log.e(TAG, "Invalid timeRangeSelectionValue: $timeRangeSelectionValue")
return 0
}
} }
} }
fun spanToLabel(span: Int): String { fun spanToLabel(span: Int): String {
//simpleDateFormat = SimpleDateFormat("dd/MM/yyyy")
//val dateTime = simpleDateFormat.format(Date(1000 * spanToUnix(span))).toString()
val dateTime = Calendar.getInstance() val dateTime = Calendar.getInstance()
dateTime.time = Date(1000 * spanToUnix(span)) dateTime.time = Date(1000 * spanToUnix(span))
val year = dateTime.get(Calendar.YEAR) val year = dateTime.get(Calendar.YEAR)
@@ -168,21 +472,42 @@ class StatisticsActivity : AppCompatActivity() {
} }
} }
} }
/*
fun calcDay(seconds: Long): Long {
val formatter = SimpleDateFormat("yyyy-MM-dd HH:mm")
val dateTime = Calendar.getInstance()
dateTime.time = Date(seconds * 1000)
val before = formatter.format(dateTime.time)
dateTime.set(Calendar.SECOND, 0)
dateTime.set(Calendar.MINUTE, 0)
dateTime.set(Calendar.HOUR, 0)
dateTime.set(Calendar.HOUR_OF_DAY, 0)
val after = formatter.format(dateTime.time)
//Log.d(TAG, "calcDay: $before -> $after")
return dateTime.time.time / 1000
}
*/
if (allEvents.isNotEmpty()) { if (allEvents.isNotEmpty()) {
barChart.visibility = View.VISIBLE barChart.visibility = View.VISIBLE
noDataTextView.visibility = View.GONE noDataTextView.visibility = View.GONE
// unix time span of all events // unix time span of all events
val startUnix = allEvents.minOf { it.getStartTime() } val startUnix = allEvents.minOf { it.time }
val endUnix = allEvents.maxOf { it.getEndTime() } val endUnix = if (dataTypeSelectionValue == "AMOUNT" && eventTypeSelectionValue == "SLEEP") {
allEvents.maxOf { it.time + it.quantity }
} else {
allEvents.maxOf { it.time }
}
// convert to days, weeks or months // convert to days, weeks or months
val startSpan = unixToSpan(startUnix) val startSpan = unixToSpan(startUnix)
val endSpan = unixToSpan(endUnix) val endSpan = unixToSpan(endUnix)
//Log.d(TAG, "startUnix: $startUnix (${Date(1000 * startUnix)}), startSpan: $startSpan (${Date(1000 * spanToUnix(startSpan))}), endUnix: $endUnix (${Date(1000 * endUnix)}), endSpan: $endSpan (${Date(1000 * spanToUnix(endSpan))})") //Log.d(TAG, "startSpan: $startSpan (${Date(1000 * allEvents.first().time)}), endSpan: $endSpan (${Date(1000 * allEvents.last().time)})")
for (span in startSpan..endSpan) { //Log.d(TAG, "start: ${Date(1000 * spanToUnix(startSpan))}, end: ${Date(1000 * spanToUnix(endSpan))}")
for (span in startSpan..endSpan + 1) {
//Log.d(TAG, "step: ${Date(1000 * daysToUnix(span))}") // todo: checj month
values.add(BarEntry(values.size.toFloat(), 0F)) values.add(BarEntry(values.size.toFloat(), 0F))
labels.add(spanToLabel(span)) labels.add(spanToLabel(span))
} }
@@ -192,29 +517,34 @@ class StatisticsActivity : AppCompatActivity() {
if (eventTypeSelectionValue == "SLEEP") { if (eventTypeSelectionValue == "SLEEP") {
// a sleep event can span to another day // a sleep event can span to another day
// distribute sleep time over the days // distribute sleep time over the days
val startUnix = event.getStartTime()
val endUnix = event.getEndTime() // iterate over indexes
// sleep covers a time range, distribute range of time spans
//var mid = spanToUnix(startIndex)
val startUnix = event.time
val endUnix = event.time + event.quantity
val begIndex = unixToSpan(startUnix) val begIndex = unixToSpan(startUnix)
val endIndex = unixToSpan(endUnix) val endIndex = unixToSpan(endUnix)
var mid = startUnix var mid = startUnix
//Log.d(TAG, "startUnix: ${Date(startUnix * 1000)}, endUnix: ${Date(endUnix * 1000)}, begIndex: $begIndex, endIndex: $endIndex (index diff: ${endIndex - begIndex})") Log.d(TAG, "startUnix: ${Date(startUnix * 1000)}, endUnix: ${Date(endUnix * 1000)}, begIndex: $begIndex, endIndex: $endIndex (index diff: ${endIndex - begIndex})")
for (i in begIndex..endIndex) { for (i in begIndex..endIndex) {
val spanBegin = spanToUnix(i) val spanBegin = spanToUnix(i)
val spanEnd = spanToUnix(i + 1) val spanEnd = spanToUnix(i + 1)
//Log.d(TAG, "mid: ${Date(mid * 1000)}, spanBegin: ${Date(spanBegin * 1000)}, spanEnd: ${Date(spanEnd * 1000)}, endUnix: ${Date(endUnix * 1000)}") Log.d(TAG, "mid: ${Date(mid * 1000)}, spanBegin: ${Date(spanBegin * 1000)}, spanEnd: ${Date(spanEnd * 1000)}, endUnix: ${Date(endUnix * 1000)}")
val beg = max(mid, spanBegin) val beg = max(mid, spanBegin)
val end = min(endUnix, spanEnd) val end = min(endUnix, spanEnd)
val index = i - startSpan val index = i - startSpan
val duration = end - beg val duration = end - beg
//Log.d(TAG, "[$index] beg: ${Date(beg * 1000)}, end: ${Date(end * 1000)}, ${formatTimeDuration(this, duration)}") Log.d(TAG, "[$index] beg: ${Date(beg * 1000)}, end: ${Date(end * 1000)}, ${formatTimeDuration(this, duration)}")
values[index].y += duration values[index].y += duration
mid = end mid = end
} }
} else { } else {
val index = unixToSpan(event.time) - startSpan val index = unixToSpan(event.time) - startSpan
//Log.d(TAG, "[${index}] ${event.quantity}")
values[index].y += event.quantity values[index].y += event.quantity
} }
} else { } else {
@@ -227,47 +557,98 @@ class StatisticsActivity : AppCompatActivity() {
noDataTextView.visibility = View.VISIBLE noDataTextView.visibility = View.VISIBLE
} }
barChart.xAxis.setLabelCount(min(values.size, 24)) val set1 = BarDataSet(values, "sums") // change to "sums", "events", "" and set logbookName to
val set1 = BarDataSet(values, "")
set1.setDrawValues(true) set1.setDrawValues(true)
set1.setDrawIcons(false) set1.setDrawIcons(false)
//Log.d("StatisticsActivity", "values.size: ${values.size}, labels.size: ${labels.size}")
//Log.d("StatisticsActivity", "values: ${values}, labels: ${labels}")
/*
val set1: BarDataSet
if (barChart.data != null &&
barChart.data.getDataSetCount() > 0
) {
set1 = barChart.data.getDataSetByIndex(0) as BarDataSet
set1.setValues(values)
barChart.data.notifyDataChanged()
barChart.notifyDataSetChanged()
} else {
*/
val dataSets = ArrayList<IBarDataSet?>() val dataSets = ArrayList<IBarDataSet?>()
dataSets.add(set1) dataSets.add(set1)
val data = BarData(dataSets) val data = BarData(dataSets)
//data.setValueTextSize(10f)
//data.setValueTypeface(tfLight)
//data.barWidth = 9f
data.setValueFormatter(object : ValueFormatter() { data.setValueFormatter(object : ValueFormatter() {
override fun getFormattedValue(value: Float): String { override fun getFormattedValue(value: Float): String {
//Log.d(TAG, "getFormattedValue ${dataTypeSelectionValue} ${eventTypeSelectionValue}") if (dataTypeSelectionValue == "AMOUNT") {
return when (dataTypeSelectionValue) { //Log.d(TAG, "formatEventValue: ${formatEventValue(value)}")
"EVENT" -> value.toInt().toString() //Log.d(TAG, "data.setValueFormatter")
"AMOUNT" -> when (eventTypeSelectionValue) { return formatEventValue(value)
"BOTTLE" -> NumericUtils(applicationContext).formatEventQuantity(LunaEvent.TYPE_BABY_BOTTLE, value.toInt()) } else {
"SLEEP" -> NumericUtils(applicationContext).formatEventQuantity(LunaEvent.TYPE_SLEEP, value.toInt()) return value.toInt().toString()
else -> {
Log.e(TAG, "unhandled eventTypeSelectionValue: $eventTypeSelectionValue")
value.toInt().toString()
}
} else -> {
Log.e(TAG, "unhandled dataTypeSelectionValue: $dataTypeSelectionValue")
value.toInt().toString()
}
} }
} }
}) })
barChart.xAxis.valueFormatter = object: ValueFormatter() { //barChart.xAxis.setLabelsToSkip(0)
//val leftAxis = barChart.axisLeft
//barChart.xAxis.setLabelCount(values.size)
barChart.axisRight.setDrawLabels(false)
barChart.axisLeft.setDrawLabels(false)
barChart.xAxis.valueFormatter = object : ValueFormatter() {
override fun getFormattedValue(value: Float): String { override fun getFormattedValue(value: Float): String {
//Log.d("labels", "labels: ${value.toInt()}")
return labels.getOrElse(value.toInt(), {"?"}) return labels.getOrElse(value.toInt(), {"?"})
} }
} }
//val labelsTmp = values.map { "${it.y.toInt()} ml" } // ArrayList<String>()
//Log.d("StatisticsActivity", "labels: $labelsTmp")
//barChart.xAxis.setGranularity(1f)
//barChart.xAxis.isGranularityEnabled = true
//barChart.xAxis.setValueFormatter(IndexAxisValueFormatter(labels))
/*
barChart.axisRight.valueFormatter = object : ValueFormatter() {
override fun getFormattedValue(value: Float): String {
//Log.d(TAG, "formatEventValue: ${formatEventValue(value)}")
return formatEventValue(value)
}
}
*/
//barChart.axisRight.setGranularity(1.0f)
//barChart.axisRight.isGranularityEnabled = true
/*
barChart.getYLabels().valueFormatter = object : ValueFormatter() {
override fun getFormattedValue(value: Float): String {
Log.d("StatisticsActivity", "y value: $value")
return value.toString() + "ml"
}
}
*/
//barChart.axisLeft.textColor = Color.WHITE
//barChart.axisRight.textColor = Color.WHITE
//barChart.setNoDataTextColor(Color.RED)
//barChart.setBackgroundColor()
//data.setValueTextSize(10f)
//data.setValueTypeface(tfLight)
//data.setBarWidth(9f)
//data.setValueTextColor(Color.WHITE)
data.setValueTextSize(12f) data.setValueTextSize(12f)
barChart.setData(data) barChart.setData(data)
barChart.invalidate() barChart.invalidate()
//}
} }
private interface SpinnerItemSelected { private interface SpinnerItemSelected {
@@ -309,23 +690,153 @@ class StatisticsActivity : AppCompatActivity() {
} }
} }
companion object { /*
const val TAG = "StatisticsActivity" fun loadSettings() {
val dataRepo = settingsRepository.loadDataRepository()
val webDavCredentials = settingsRepository.loadWebdavCredentials()
val noBreastfeeding = settingsRepository.loadNoBreastfeeding()
val signature = settingsRepository.loadSignature()
when (dataRepo) {
LocalSettingsRepository.DATA_REPO.LOCAL_FILE -> radioDataLocal.isChecked = true
LocalSettingsRepository.DATA_REPO.WEBDAV -> radioDataWebDAV.isChecked = true
}
textViewSignature.setText(signature)
switchNoBreastfeeding.isChecked = noBreastfeeding
if (webDavCredentials != null) {
textViewWebDAVUrl.text = webDavCredentials[0]
textViewWebDAVUser.text = webDavCredentials[1]
textViewWebDAVPass.text = webDavCredentials[2]
}
}
fun validateAndSave() {
if (radioDataLocal.isChecked) {
// No validation required, just save
saveSettings()
return
}
// Try to connect to WebDAV and check if the save file already exists
val webDAVLogbookRepo = WebDAVLogbookRepository(
textViewWebDAVUrl.text.toString(),
textViewWebDAVUser.text.toString(),
textViewWebDAVPass.text.toString()
)
progressIndicator.visibility = View.VISIBLE
webDAVLogbookRepo.listLogbooks(this, object: LogbookListObtainedListener{
override fun onLogbookListObtained(logbooksNames: ArrayList<String>) {
if (logbooksNames.isEmpty()) {
// TODO: Ask the user if he wants to upload the local ones or to create a new one
copyLocalLogbooksToWebdav(webDAVLogbookRepo, object: OnCopyLocalLogbooksToWebdavFinishedListener {
override fun onCopyLocalLogbooksToWebdavFinished(errors: String?) {
runOnUiThread({
progressIndicator.visibility = View.INVISIBLE
if (errors == null) {
saveSettings()
Toast.makeText(this@SettingsActivity, R.string.settings_webdav_creation_ok, Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this@SettingsActivity, errors, Toast.LENGTH_SHORT).show()
}
})
}
})
} else {
runOnUiThread({
progressIndicator.visibility = View.INVISIBLE
saveSettings()
Toast.makeText(this@SettingsActivity, R.string.settings_webdav_creation_ok, Toast.LENGTH_SHORT).show()
})
}
}
override fun onIOError(error: IOException) {
runOnUiThread({
progressIndicator.visibility = View.INVISIBLE
Toast.makeText(this@SettingsActivity, getString(R.string.settings_network_error) + error.toString(), Toast.LENGTH_SHORT).show()
})
}
override fun onWebDAVError(error: SardineException) {
runOnUiThread({
progressIndicator.visibility = View.INVISIBLE
if(error.toString().contains("401")) {
Toast.makeText(this@SettingsActivity, getString(R.string.settings_webdav_error_denied), Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this@SettingsActivity, getString(R.string.settings_webdav_error_generic) + error.toString(), Toast.LENGTH_SHORT).show()
}
})
}
override fun onError(error: Exception) {
runOnUiThread({
progressIndicator.visibility = View.INVISIBLE
Toast.makeText(this@SettingsActivity, getString(R.string.settings_generic_error) + error.toString(), Toast.LENGTH_SHORT).show()
})
}
})
}
fun saveSettings() {
settingsRepository.saveDataRepository(
if (radioDataWebDAV.isChecked) LocalSettingsRepository.DATA_REPO.WEBDAV
else LocalSettingsRepository.DATA_REPO.LOCAL_FILE
)
settingsRepository.saveNoBreastfeeding(switchNoBreastfeeding.isChecked)
settingsRepository.saveSignature(textViewSignature.text.toString())
settingsRepository.saveWebdavCredentials(
textViewWebDAVUrl.text.toString(),
textViewWebDAVUser.text.toString(),
textViewWebDAVPass.text.toString()
)
finish()
}
private fun copyLocalLogbooksToWebdav(webDAVLogbookRepository: WebDAVLogbookRepository, listener: OnCopyLocalLogbooksToWebdavFinishedListener) {
Thread(Runnable {
val errors = StringBuilder()
val fileLogbookRepo = FileLogbookRepository()
val logbooks = fileLogbookRepo.getAllLogbooks(this)
for (logbook in logbooks) {
// Copy only if does not already exist
val error = webDAVLogbookRepository.uploadLogbookIfNotExists(this, logbook.name)
if (error != null) {
if (errors.isNotEmpty())
errors.append("\n")
errors.append(String.format(getString(R.string.settings_webdav_upload_error), logbook.name, error))
}
}
listener.onCopyLocalLogbooksToWebdavFinished(
if (errors.isEmpty()) null else errors.toString()
)
}).start()
}
private interface OnCopyLocalLogbooksToWebdavFinishedListener {
fun onCopyLocalLogbooksToWebdavFinished(errors: String?)
}
*/
companion object {
fun unixToMonths(seconds: Long): Int { fun unixToMonths(seconds: Long): Int {
val dateTime = Calendar.getInstance() val dateTime = Calendar.getInstance()
dateTime.time = Date(seconds * 1000) dateTime.time = Date(seconds * 1000)
val years = dateTime.get(Calendar.YEAR) val years = dateTime.get(Calendar.YEAR)
val months = dateTime.get(Calendar.MONTH) val months = dateTime.get(Calendar.MONTH) // January is 0
return 12 * years + months return 12 * years + 1 + months
} }
fun monthsToUnix(months: Int): Long { fun monthToUnix(months: Int): Long {
val dateTime = Calendar.getInstance() val dateTime = Calendar.getInstance()
dateTime.time = Date(0) dateTime.time = Date(0)
dateTime.set(Calendar.YEAR, months / 12) dateTime.set(Calendar.YEAR, months / 12)
dateTime.set(Calendar.MONTH, months % 12) dateTime.set(Calendar.MONTH, months % 12)
//Calendar.MONTH_OF_YEAR?
dateTime.set(Calendar.HOUR, 0) dateTime.set(Calendar.HOUR, 0)
dateTime.set(Calendar.MINUTE, 0) dateTime.set(Calendar.MINUTE, 0)
dateTime.set(Calendar.SECOND, 0) dateTime.set(Calendar.SECOND, 0)
@@ -344,8 +855,7 @@ class StatisticsActivity : AppCompatActivity() {
val dateTime = Calendar.getInstance() val dateTime = Calendar.getInstance()
dateTime.time = Date(0) dateTime.time = Date(0)
dateTime.set(Calendar.YEAR, weeks / 52) dateTime.set(Calendar.YEAR, weeks / 52)
dateTime.set(Calendar.WEEK_OF_YEAR, weeks % 52) dateTime.set(Calendar.DAY_OF_YEAR, weeks % 52)
dateTime.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY)
dateTime.set(Calendar.HOUR, 0) dateTime.set(Calendar.HOUR, 0)
dateTime.set(Calendar.MINUTE, 0) dateTime.set(Calendar.MINUTE, 0)
dateTime.set(Calendar.SECOND, 0) dateTime.set(Calendar.SECOND, 0)

View File

@@ -59,7 +59,7 @@ class LunaEventRecyclerAdapter: RecyclerView.Adapter<LunaEventRecyclerAdapter.Lu
LunaEvent.TYPE_CUSTOM -> item.notes LunaEvent.TYPE_CUSTOM -> item.notes
else -> item.getTypeDescription(context) else -> item.getTypeDescription(context)
} }
holder.time.text = DateUtils.formatTimeAgo(context, item.getEndTime()) holder.time.text = DateUtils.formatTimeAgo(context, item.time)
var quantityText = numericUtils.formatEventQuantity(item) var quantityText = numericUtils.formatEventQuantity(item)
// if the event is weight, show difference with the last one // if the event is weight, show difference with the last one

View File

@@ -94,18 +94,6 @@ class LunaEvent: Comparable<LunaEvent> {
this.quantity = quantity this.quantity = quantity
} }
fun getStartTime(): Long {
return time
}
fun getEndTime(): Long {
return if (type == TYPE_SLEEP) {
time + quantity
} else {
time
}
}
fun getTypeEmoji(context: Context): String { fun getTypeEmoji(context: Context): String {
return context.getString( return context.getString(
when (type) { when (type) {

View File

@@ -39,4 +39,11 @@
<item>MONTH</item> <item>MONTH</item>
</string-array> </string-array>
<!--
<string-array name="speakerphoneModeValues">
<item>auto</item>
<item>on</item>
<item>off</item>
</string-array>
-->
</resources> </resources>