package org.foxarmy.barcodescannerforemployees

import android.util.Log
import org.foxarmy.barcodescannerforemployees.dataclasses.AbstractProduct

class Parser constructor() {

    fun findNetWeightInText(text: String, regexes: List<Regex>): Triple<String, Double, String> {
        var text = text
        var netWeight = 0.0
        for (regex in regexes.iterator()) {
            val foundByRegex = regex.find(text)
            if (foundByRegex != null) {
                val found = foundByRegex.groupValues[0]
                text = text.replace(found, "")
                netWeight = stripNetWeight(found)
//                when (found.lowercase().strip()) {
//                    "кг" -> netWeight *= 1000
//                    "мл" -> netWeight /= 1000
//                }
                return Triple(text, netWeight, found)
            }
        }
        return Triple("", 0.0, "")
    }

    fun parse(text: String): AbstractProduct {
        val (name, netWeight, unit) = findNetWeightInText(
            text,
            listOf(
                Regex("[0-9]+,?[0-9]*\\s*[лЛ]"),
                Regex("[0-9]+,?[0-9]*\\s*((мл)|(МЛ)|(Мл))"),
                Regex("[0-9]+,?[0-9]*\\s*((кг)|(Кг))"),
                Regex("[0-9]+,?[0-9]*\\s*[гГ]"),
                Regex("[0-9]+,?[0-9*]\\s*((шт)|(Шт))")
            )
        )
        var unitNumber = -1
        val strippedUnit = unit.lowercase().replace(Regex("\\d"), "").strip()
        unitNumber = when (strippedUnit) {
            "кг" -> { 0 }
            "г" -> { 1 }
            "л" -> { 2 }
            "мл" -> { 3 }
            "шт" -> { 4 }

            else -> { -1 }
        }
        Log.d("QWERTYUIOP", "Unit: ${strippedUnit}, number: ${unitNumber}")

        return AbstractProduct(0, "", name, netWeight, "", 0, unitNumber)
    }
}