Bimba.git

ref: e4d7079147c16b0d67cd39e35f5d943644d24c68

app/src/main/java/xyz/apiote/bimba/czwek/units/imperial.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
package xyz.apiote.bimba.czwek.units

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

object Imperial : 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 = MiYd(count)
	override fun distanceUnit(other: DistanceUnit): DistanceUnit = MiYd(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 Miph(val miph: Double) : SpeedUnit {
	constructor(s: Int) : this(s.toDouble())
	constructor(other: SpeedUnit) : this(other.mps() / 0.44704)

	override fun mps(): Double = miph * 0.44704
	override fun toString(context: Context, base: Int): String =
		context.getString(
			R.string.speed_in_mi_per_h,
			NumberFormat.getInstance().apply { maximumFractionDigits = 2 }.format(miph)
		)

	override fun contentDescription(context: Context, base: Int): String =
		context.resources.getQuantityString(
			R.plurals.speed_in_mi_per_h_cd, miph.toInt(), miph.toInt()
		)
}

class MiYd(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_yd,
				NumberFormat.getIntegerInstance().format((mi * 1760).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_yd_cd,
				(mi / 1760).toInt(),
				(mi / 1760).toInt()
			)
		} else {
			val miles = mi.toInt()
			val yards = ((mi - miles) * 1760).toInt()
			val miString = context.resources.getQuantityString(R.plurals.distance_in_mi_cd, miles)
			val ydString = context.resources.getQuantityString(R.plurals.distance_in_yd_cd, yards)
			if (yards > 0) {
				context.getString(R.string.distance_in_two_units_cd, miString, ydString)
			} else {
				miString
			}
		}
}