package com.sd.hmct_small_model

import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import org.tensorflow.lite.Interpreter
import org.tensorflow.lite.support.common.FileUtil
import org.tensorflow.lite.support.label.Category
import java.io.IOException

class TensorFlowVm : ViewModel() {

    private var interpreter: Interpreter? = null
    var isInitialized = false

//    private var context: Context? = null

    fun initialize(context: Context) {
        try {
            val assetManager = context.assets
            val model = FileUtil.loadMappedFile(context, "deberta_v3_xsmall_qa_fixed.tflite")
            val interpreter = Interpreter(model)

            // TODO: Read the model input shape from model file.

            // Read input shape from model file.
//            val inputShape = interpreter.getInputTensor(0).shape()
//            inputImageWidth = inputShape[1]
//            inputImageHeight = inputShape[2]
//            modelInputSize = FLOAT_TYPE_SIZE * inputImageWidth *
//                    inputImageHeight * PIXEL_SIZE

            // Finish interpreter initialization.
            this.interpreter = interpreter

            isInitialized = true
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }


    fun answerEt(string: String, context: Context) {
//        val byteBuffer = convertBitmapToByteBuffer(resizedImage)
        // Define an array to store the model output.
        val output = Array(1) { FloatArray(OUTPUT_CLASSES_COUNT) }

        // Run inference with the input data.
//        interpreter?.run(byteBuffer, output)

    }


    fun close() {
        viewModelScope.launch {
            interpreter?.close()
        }
    }


    companion object {
        private const val TAG = "DigitClassifier"

        private const val FLOAT_TYPE_SIZE = 4
        private const val PIXEL_SIZE = 1

        private const val OUTPUT_CLASSES_COUNT = 128
    }


}
