package sh.moritz.watchcalculator.presentation

import kotlin.math.round

class FormulaSolver (val formula: String) {
	fun Solve(): String {
		if (formula.isEmpty()) {
			return 0.toString()
		}
		val tokens = formula.replace("×", "*").replace("÷", "/")

		// Simple tokenizer: split into numbers and operators
		val parts = Regex("(?<=[+\\-*/])|(?=[+\\-*/])").split(tokens).filter { it.isNotEmpty() }

		// First, handle * and /
		val stack = mutableListOf<String>()
		var i = 0
		while (i < parts.size) {
			val token = parts[i]
			when (token) {
				"*" -> {
					val prev = stack.removeAt(stack.lastIndex).toDouble()
					val next = parts[++i].toDouble()
					stack.add((prev * next).toString())
				}
				"/" -> {
					val prev = stack.removeAt(stack.lastIndex).toDouble()
					val next = parts[++i].toDouble()
					stack.add((prev / next).toString())
				}
				else -> stack.add(token)
			}
			i++
		}

		// Then, handle + and -
		var result = stack[0].toDouble()
		i = 1
		while (i < stack.size) {
			when (stack[i]) {
				"+" -> result += stack[++i].toDouble()
				"-" -> result -= stack[++i].toDouble()
			}
			i++
		}

		return (round(result*100)/100).toString().trimEnd('0').trimEnd('.')
	}
}