package org.needhamtrack.nytc.utils

import org.needhamtrack.nytc.models.Fraction
import org.needhamtrack.nytc.models.Mark

object MarkParser {
    fun fromString(rawMark: String): Mark {
        if (rawMark.indexOf('-') < 0) {
            throw IllegalArgumentException("must use a - to separate feet and inches")
        }
        if (rawMark.indexOf('.') < 0) {
            throw IllegalArgumentException("must use a . in inch marker")
        }
        val feetInchesSplit = rawMark.split('-')
        val feet = feetInchesSplit[0].toInt()
        val totalInches = feetInchesSplit[1].toDouble()
        val fractionInches = mantissa(totalInches)
        val wholeInches = Math.floor(totalInches - fractionInches).toInt()
        val fraction = bucket(Math.floor(100 * fractionInches).toInt())
        return Mark(feet, wholeInches, fraction)
    }

    private fun mantissa(number: Double) = number - Math.floor(number)

    private fun bucket(number: Int): Fraction {
        when (number) {
            in 0..24 -> return Fraction.ZERO
            in 25..49 -> return Fraction.ONE_QUARTER
            in 50..74 -> return Fraction.HALF
            in 75..99 -> return Fraction.THREE_QUARTERS
        }
        throw IllegalArgumentException("number was $number, but must in [0, 99]")
    }

    // possible regex: \d{1,}-\d{2}[.]\d{2}
}