package com.sd.hmct_small_model

import android.content.Context
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.pytorch.IValue
//import org.pytorch.LiteModuleLoader
import org.pytorch.Module
import org.pytorch.Tensor
//import org.pytorch.executorch.EValue;
//import org.pytorch.executorch.Module;
//import org.pytorch.executorch.Tensor;
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStream


class TorchscriptDemo(private val context: Context) {

    var module: Module? = null

    suspend fun initializeInterpreter() {
        // app/src/model/assets/model.pt
        var fPath = withContext(Dispatchers.IO) {
            assetFilePath(context, "slot_model_torchscript.pt")
//            true
//            var a = 0
        }
        if (fPath.isEmpty())
            return
        try {
//            module = PyTorchAndroid.loadModuleFromAsset(context.assets, "intent_model_traced.pt")
             module = Module.load(fPath)
//            module = LiteModuleLoader.load(fPath)
            var a = 0
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


//    fun ask(tensor: Tensor) :Tensor{
////        val eValue1: EValue = EValue.from(tensor)
////        val result = module!!.forward(eValue1)[0].toTensor().getDataAsFloatArray()[0]
////        val result = module!!.forward(eValue1)[0].toTensor()
//        return result
//    }


//    fun ask(tensor: Tensor) :Tensor?{
////        val outTensors = module!!.forward(IValue.from(tensor)).toTensor()
////        return outTensors
//        return null
//    }


    /**
     * Copies specified asset to the file in /files app directory and returns this file absolute path.
     *
     * @return absolute file path
     */
    fun assetFilePath(context: Context, assetName: String): String {
        val file = File(context.filesDir, assetName)
        if (file.exists() && file.length() > 0) {
            return file.absolutePath
        }
        try {
            var inputs = context.assets.open(assetName)
            var os: OutputStream = FileOutputStream(file)
            val buffer = ByteArray(4 * 1024)
            var read: Int
            while ((inputs.read(buffer).also { read = it }) != -1) {
                os.write(buffer, 0, read)
            }
            os.flush()
            return file.absolutePath
        } catch (e: IOException) {
            return ""
        }
    }


    fun close() {

    }

}