// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: AGPL-3.0-or-later

package xyz.apiote.bimba.czwek.units

import android.content.Context
import xyz.apiote.bimba.czwek.R
import java.text.NumberFormat

object USCustomary : UnitSystem(10) {
	override fun timeUnit(count: Long): TimeUnit = Second(count.toDouble())
	override fun timeUnit(other: TimeUnit): TimeUnit = Second(other)

	override fun speedUnit(count: Double): SpeedUnit = Miph(count)
	override fun speedUnit(other: SpeedUnit): SpeedUnit = Miph(other)

	override fun distanceUnit(count: Double): DistanceUnit = MiFt(count)
	override fun distanceUnit(other: DistanceUnit): DistanceUnit = MiFt(other)

	override fun toString(context: Context, s: SpeedUnit): String = s.toString(context, base)
	override fun toString(context: Context, t: TimeUnit): String = t.toString(context, base)
	override fun toString(context: Context, d: DistanceUnit): String = d.toString(context, base)
}

class MiFt(val mi: Double) : DistanceUnit {
	constructor(other: DistanceUnit) : this(other.meters() / 1609.344)

	override fun meters(): Double = mi * 1609.344

	override fun toString(context: Context, base: Int): String = if (mi < 1) {
		context.getString(
			R.string.distance_in_ft,
			NumberFormat.getIntegerInstance().format((mi * 5280).toInt())
		)
	} else {
		context.getString(
			R.string.distance_in_mi,
			NumberFormat.getInstance().apply { maximumFractionDigits = 2 }.format(mi)
		)
	}

	override fun contentDescription(context: Context, base: Int): String =
		if (mi < 1) {
			context.resources.getQuantityString(R.plurals.distance_in_ft_cd, (mi * 5280).toInt())
		} else {
			val miles = mi.toInt()
			val feet = ((mi - miles) * 5280).toInt()
			val miString = context.resources.getQuantityString(R.plurals.distance_in_mi_cd, miles)
			val ftString = context.resources.getQuantityString(R.plurals.distance_in_ft_cd, feet)
			if (feet > 0) {
				context.getString(R.string.distance_in_two_units_cd, miString, ftString)
			} else {
				miString
			}
		}
}
