package net.pokeranalytics.android.util.extensions

import android.content.Context
import net.pokeranalytics.android.R
import java.lang.Math.abs
import java.math.RoundingMode
import java.text.DecimalFormat
import java.text.NumberFormat
import java.util.*

fun Number.kmbFormatted(threshold: Double = 10000.0): String {
	var thousandsExponent = 0
	var v = this.toDouble()
	if (abs(v) >= threshold) {
		while (abs(v) >= 1000 && thousandsExponent < 3) {
			v /= 1000
			thousandsExponent++
		}
	}

	val unit = when (thousandsExponent) {
		0 -> ""
		1 -> "K"
		2 -> "M"
		3 -> "B"
		else -> "B+" // shouldn't happen
	}

	val formatter = NumberFormat.getInstance()
	return formatter.format(v) + unit
}

// Double

fun Double.round(): String {
	val formatter = DecimalFormat("##.##")
	return formatter.format(this)
}

fun Double.roundOffDecimal(): Double {
    return this.toBigDecimal().setScale(2, RoundingMode.CEILING).toDouble()
}

fun Double.formatted(): String {
	val format = NumberFormat.getNumberInstance()
	format.maximumFractionDigits = 2
	format.minimumFractionDigits = 0
	return format.format(this)
}

fun Double.toCurrency(currency: Currency? = null): String {

	val currencyFormatter = NumberFormat.getCurrencyInstance()
	currency?.let {
		currencyFormatter.currency = currency
	}

	currencyFormatter.maximumFractionDigits = 2
	currencyFormatter.minimumFractionDigits = 0
	return currencyFormatter.format(this)
}


fun Double.toRate(): String {
	val currencyFormatter = NumberFormat.getInstance()
	currencyFormatter.minimumFractionDigits = 0
	currencyFormatter.maximumFractionDigits = 6
	return currencyFormatter.format(this)
}

fun Double.formattedHourlyDuration(): String {
	return (this * 1000 * 3600).toLong().toMinutes()
}

// Return the time from minutes to hours:minutes
fun Int.toMinutes(context: Context): String {
	val hours = this / 60
	val minutesLeft = this % 60
	var duration = ""

	if (hours < 1) {
		duration += "$minutesLeft ${context.getString(if (minutesLeft > 1) R.string.mins else R.string.min)}"
	} else {
		duration += hours.toString()
		duration += ":"
		duration += if (minutesLeft < 10) "0$minutesLeft" else minutesLeft.toString()
	}

	return duration
}

// Return the time from milliseconds to hours:minutes
fun Long.toMinutes(): String {
	val totalMinutes = this / (1000 * 60)
	val hours = totalMinutes / 60
	val minutesLeft = totalMinutes % 60
	var duration = ""
	duration += hours.toString()
	duration += ":"
	duration += if (minutesLeft < 10) "0$minutesLeft" else minutesLeft.toString()
	return duration
}