package com.lovable.zellyfinance;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;

import com.getcapacitor.JSObject;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;
import com.getcapacitor.PluginCall;

import java.io.ByteArrayOutputStream;

@CapacitorPlugin(name = "ImagePlugin")
public class ImagePlugin extends Plugin {

    @PluginMethod
    public void getResourceImage(PluginCall call) {
        String resourceName = call.getString("resourceName");
        
        if (resourceName == null) {
            call.reject("Resource name is required");
            return;
        }

        try {
            // 리소스 ID 찾기
            int resourceId = getContext().getResources().getIdentifier(
                resourceName, "drawable", getContext().getPackageName());
            
            if (resourceId == 0) {
                call.reject("Resource not found: " + resourceName);
                return;
            }

            // 비트맵으로 변환
            Bitmap bitmap = BitmapFactory.decodeResource(getContext().getResources(), resourceId);
            
            // Base64로 인코딩
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
            byte[] byteArray = byteArrayOutputStream.toByteArray();
            String base64Image = Base64.encodeToString(byteArray, Base64.DEFAULT);
            
            // 응답 생성
            JSObject ret = new JSObject();
            ret.put("base64Image", "data:image/png;base64," + base64Image);
            call.resolve(ret);
            
        } catch (Exception e) {
            call.reject("Error loading image", e);
        }
    }
}
