package theorycrafter.utils


/**
 * The result of parsing the item text typed by the user.
 */
class ParsedItemWithAmount(val itemName: String, val amount: Int, val hasAmountOnly: Boolean)


/**
 * Parses the text typed by the user into an item name and an amount.
 * We want to allow these formats:
 * - <amount>x<name>
 * - <amount>x <name>
 * - <amount> x <name>
 * - <amount> <name>
 * - <name> (amount is 1)
 * - <amount> (name is current item)
 */
fun parseItemWithAmountText(currentItemName: String?, text: String): ParsedItemWithAmount {
    var amountPartEndIndex = text.indexOfAny(charArrayOf(' ', 'x'))
    if (amountPartEndIndex == -1)
        amountPartEndIndex = text.length

    val amountPart = text.substring(0, amountPartEndIndex)
    val amount = amountPart.toIntOrNull()
    if (amount == null)  // The amount part was not actually an amount
        return ParsedItemWithAmount(itemName = text, 1, hasAmountOnly = false)

    val itemPart = text.substring((amountPartEndIndex+1).coerceAtMost(text.length))
    val itemName = when {
        itemPart.startsWith("x ") -> itemPart.substring(2)
        itemPart.startsWith("x") -> itemPart.substring(1)
        itemPart.startsWith(" ") -> itemPart.substring(1)
        else -> itemPart
    }

    return if (itemPart.isBlank() && (currentItemName != null))
        ParsedItemWithAmount(currentItemName, amount, hasAmountOnly = true)
    else
        ParsedItemWithAmount(itemName, amount, hasAmountOnly = false)
}


/**
 * Returns the string an item with an amount should be displayed as.
 */
fun String.withAmount(amount: Int) = "${amount}x $this"