package com.feelpay.app;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.util.Base64;
import android.util.Log;

import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;

import androidx.core.app.ActivityCompat;

import com.dantsu.escposprinter.EscPosPrinter;
import com.dantsu.escposprinter.connection.bluetooth.BluetoothPrintersConnections;
import com.dantsu.escposprinter.textparser.PrinterTextParserImg;



public class FeelNative {
    private static final String TAG = "FeelNative";

    public void print(String base64Data, String printerName, String address) {
        try {
            // Remove the data URI prefix if present (e.g., "data:image/png;base64,")
            if (base64Data.startsWith("data:image")) {
                base64Data = base64Data.substring(base64Data.indexOf(",") + 1);
            }

            // Decode the Base64 string into a byte array and then to a Bitmap
            byte[] imageBytes = Base64.decode(base64Data, Base64.DEFAULT);
            Bitmap receiptBitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
            if (receiptBitmap == null) {
                Log.e("Printer", "Failed to decode receipt image.");
                return;
            }

            // Create a printer connection. The example uses the first paired printer,
            // but you could also create a Bluetooth connection using the provided address.
            // For instance:
            // PrinterBluetooth printerBluetooth = new PrinterBluetooth(address);
            // And then pass that to your printer constructor.
            // Here we use the library’s built-in helper:
            EscPosPrinter printer = new EscPosPrinter(
                    BluetoothPrintersConnections.selectFirstPaired(), // Connection
                    203,  // Printer DPI or width parameter
                    48f,  // Font size (or similar scale parameter)
                    32    // Number of characters per line (or margin setting)
            );

            // Convert the Bitmap to a hexadecimal string using the provided printer instance.
            String imageHex = PrinterTextParserImg.bitmapToHexadecimalString(printer, receiptBitmap);

            // Build your formatted text. The example below simply prints the image centered.
            // You can add additional formatting tags as in your provided sample.
            String formattedText = "[C]<img>" + imageHex + "</img>\n" +
                    "[L]\n" +
                    "[C]<u><font size='big'>" + printerName + "</font></u>\n" +
                    "[L]"; // Add any additional formatted text as needed.

            // Print the formatted text
            printer.printFormattedText(formattedText);

        } catch (Exception e) {
            Log.e("Printer", "Error while printing receipt: ", e);
        }

    }
        public String getAllPrinters(Context context) {
        JSONArray printerList = new JSONArray();
        // Check Bluetooth permission
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { // Android 12+
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                Log.e(TAG, "Missing BLUETOOTH_CONNECT permission");
                return "Permission error";
            }
        } else {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED) {
                Log.e(TAG, "Missing BLUETOOTH permission");
                return "Permission error";
            }
        }

        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
            Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
            for (BluetoothDevice device : pairedDevices) {
                JSONObject printerObject = new JSONObject();
                try {
                    printerObject.put("name", device.getName());
                    printerObject.put("address", device.getAddress());
                } catch (JSONException e) {
                    Log.e(TAG, "Error creating printer JSON object", e);
                }
                printerList.put(printerObject);
            }
        } else {
            Log.e(TAG, "Bluetooth is disabled or not supported");
        }

        return printerList.toString();
    };
};
