package com.example.livingai.analysis

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.util.Log
import com.example.livingai.commons.Constants
import java.io.File

class SavedMaskProcessor(private val context: Context) {

    fun loadSavedMask(orientation: String): Bitmap? {
        val filename = "${orientation}_mask.png"
        val file = File(context.filesDir, filename)
        var savedMaskBitmap: Bitmap? = null

        if (file.exists()) {
            try {
                val savedBitmap = BitmapFactory.decodeFile(file.absolutePath)

                if (savedBitmap != null) {
                    //TODO: Added for debug can be removed safely
                    savedMaskBitmap = applyGreenColor(savedBitmap)
                }

            } catch (e: Exception) {
                Log.e("SavedMaskProcessor", "Error loading saved mask", e)
            }
        }
        return savedMaskBitmap
    }

    //TODO: Added for debug can be removed safely
    private fun applyGreenColor(original: Bitmap): Bitmap {
        val width = original.width
        val height = original.height
        val pixels = IntArray(width * height)
        original.getPixels(pixels, 0, width, 0, 0, width, height)
        for (i in pixels.indices) {
            val alpha = (pixels[i] shr 24) and 0xff
            if (alpha > 10) {
                pixels[i] = Color.argb(alpha, 0, 255, 0)
            }
        }
        return Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888)
    }
}
