package com.sogeti.quantumleap.uielements import android.content.Context import android.view.ViewGroup import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.viewinterop.AndroidView import io.data2viz.charts.chart.Chart import io.data2viz.charts.chart.chart import io.data2viz.charts.chart.discrete import io.data2viz.charts.chart.mark.bar import io.data2viz.charts.chart.quantitative import io.data2viz.geom.Size import io.data2viz.random.RandomDistribution import io.data2viz.viz.VizContainerView import kotlin.random.Random // Data class to represent population counts data class PopCount(val year: Int, val population: Double) // Composable function to display the chart @Composable fun Data2VizChart( modifier: Modifier = Modifier, maxYValue: Double = 8000.0, // Default maximum Y value barCount: Int = 30, // Default number of bars data: List<PopCount> = generateRandomData(barCount, maxYValue) // Generate random data ) { AndroidView( modifier = modifier, factory = { context -> CanadaChart(context).apply { layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ) } }, update = { view -> view.updateChartData(data) } ) } // Utility function to generate random data fun generateRandomData(barCount: Int, maxYValue: Double): List<PopCount> { val generator = RandomDistribution.uniform(max = maxYValue) return List(barCount) { index -> PopCount(index, generator().toDouble()) } } class CanadaChart(context: Context) : VizContainerView(context) { // Current data of the chart private var currentData: List<PopCount> = listOf() // Initially create the chart with the current data and a size of 0.0 by 0.0 var chart: Chart<PopCount> = createChart(currentData, Size(0.0, 0.0)) // This method will create a chart with given data and size private fun createChart(data: List<PopCount>, size: Size): Chart<PopCount> { return chart(data) { this.size = size title = "Population of Canada 1851–2001 (Statistics Canada)" val year = discrete({ domain.year }) val population = quantitative({ domain.population }) { name = "Population (millions)" } bar(year, population) } } // Call this method to update the chart data fun updateChartData(newData: List<PopCount>) { currentData = newData chart = createChart(newData, Size(width.toDouble(), height.toDouble())) invalidate() } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) // Update the chart with the new size chart = createChart(currentData, Size(w.toDouble(), h.toDouble())) invalidate() } }