package es.verdnatura.presentation.common

import android.os.Build
import androidx.annotation.RequiresApi
import org.json.JSONObject
import java.time.format.DateTimeFormatter

data class ItemScanned(var scanned: JSONObject) {
    var table: String = scanned.get("table").toString()
    var id: Int = scanned.get("id").toString().toInt()
    var company: String = scanned.get("company").toString()
    var more: String = if (scanned.has("more")) scanned.get("more").toString() else ""
    var user: Int = scanned.get("user").toString().toInt()

    @RequiresApi(Build.VERSION_CODES.O)
    var created  = DateTimeFormatter.ISO_INSTANT.parse(scanned.get("created").toString())

}

fun itemScanIsQr(value: String): Boolean {

    return try {
        ItemScanned(JSONObject(value))
        true

    } catch (ex: Exception) {
        false
    }
}
fun itemScanValue(value: String, table: String, field: String): Any {
    val item: ItemScanned
    return try {

        try {
            item = ItemScanned(JSONObject(value))
        } catch (ex: Exception) {
            return value
        }

        if (item.company == "vnl" && item.table == table) {

            when (field) {
                "id" -> return item.id
                "more" -> return item.more

            }

        }
        throw Exception("QR no válido")

    } catch (ex: Exception) {
        throw ex
    }

}
