package net.pokeranalytics.android.util.csv

import timber.log.Timber
import java.text.DateFormat
import java.text.NumberFormat
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*

/**
 * An interface used to provide a Number flavour to a CSV field
 */
interface NumberCSVField: TypedCSVField<Double> {

	val numberFormat: String?

	override fun parse(value: String) : Double? {

		if (value.isEmpty()) {
			return null
		}

		val formatter = NumberFormat.getInstance()

		return try {
			formatter.parse(value).toDouble()
		} catch (e: ParseException) {
			Timber.d("Unparseable number: $value")
			null
		}
	}
}

interface DateCSVField : TypedCSVField<Date> {

	val dateFormat: String?

	override fun parse(value: String) : Date? {

		val formatter = if (dateFormat != null) SimpleDateFormat(dateFormat) else SimpleDateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)
		return try {
			formatter.parse(value)
		} catch (e: ParseException) {
			Timber.d("Unparseable date: $value")
			null
		}
	}

}

interface BlindCSVField : TypedCSVField<Pair<Double, Double>> {

	override fun parse(value: String) : Pair<Double, Double>? {

		this.callback?.let { cb ->
			return cb(value)
		}

		val strBlinds = value.split("/")
		if (strBlinds.size == 2) {
			val bb = strBlinds.last().toDouble()
			val sb = strBlinds.first().toDouble()
			return Pair(sb, bb)
		} else {
			Timber.d("Blinds could not be parsed: $value")
		}

		return null
	}

}

interface TypedCSVField<T> : CSVField {
	fun parse(value: String) : T?
	var callback: ((String) -> T?)?
}

interface CSVField {
	val header: String
}