package com.github.premnirmal.ticker.ui

import android.graphics.Canvas
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.formatter.ValueFormatter
import com.github.mikephil.charting.renderer.XAxisRenderer
import com.github.mikephil.charting.utils.MPPointF
import com.github.mikephil.charting.utils.Transformer
import com.github.mikephil.charting.utils.Utils
import com.github.mikephil.charting.utils.ViewPortHandler
import com.github.premnirmal.ticker.AppPreferences
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId

class DateAxisFormatter : ValueFormatter() {

    override fun getFormattedValue(
        value: Float,
    ): String {
        val date = LocalDateTime.ofInstant(Instant.ofEpochSecond(value.toLong()), ZoneId.systemDefault()).toLocalDate()
        return date.format(AppPreferences.AXIS_DATE_FORMATTER)
    }
}

class HourAxisFormatter : ValueFormatter() {

    override fun getFormattedValue(
        value: Float,
    ): String {
        val hour = LocalDateTime.ofInstant(Instant.ofEpochSecond(value.toLong()), ZoneId.systemDefault()).toLocalTime()
        return hour.format(AppPreferences.TIME_FORMATTER)
    }
}

class ValueAxisFormatter : ValueFormatter() {

    override fun getFormattedValue(
        value: Float,
    ): String =
        AppPreferences.DECIMAL_FORMAT.format(value)
}

class MultilineXAxisRenderer(
    viewPortHandler: ViewPortHandler?,
    xAxis: XAxis?,
    trans: Transformer?
) : XAxisRenderer(viewPortHandler, xAxis, trans) {

    override fun drawLabel(
        c: Canvas,
        formattedLabel: String,
        x: Float,
        y: Float,
        anchor: MPPointF,
        angleDegrees: Float
    ) {
        val lines = formattedLabel.split("-")
        for (i in 0 until lines.size) {
            val vOffset = i * mAxisLabelPaint.textSize
            Utils.drawXAxisValue(c, lines[i], x, y + vOffset, mAxisLabelPaint, anchor, angleDegrees)
        }
    }
}
