package com.shukria.softpos;

import android.content.Context;
import android.content.pm.PackageManager;
import android.nfc.NfcAdapter;

import androidx.annotation.RawRes;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.Base64;
import java.util.function.Consumer;

public class Utils {

    public static String encodeToBase64(byte[] data) {
        return Base64.getEncoder().encodeToString(data);
    }

    public static byte[] decodeBase64(String data) {
        return Base64.getDecoder().decode(data);
    }

    public static String convertToHexString(byte[] data) {
        StringBuilder sb = new StringBuilder();

        for (byte datum : data) {
            sb.append(String.format("%X0d", datum));
        }

        return sb.toString();
    }

    public static byte[] readFromRawFile(Context context, @RawRes int rawID) {
        InputStream is = context.getResources().openRawResource(rawID);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int len;
        try {
            while ((len = is.read(buf)) != -1) {
                baos.write(buf, 0, len);
            }
            baos.close();
            is.close();
        } catch (IOException e) {
            throw new RuntimeException("Error reading raw file");
        }
        return baos.toByteArray();
    }

    public enum DeviceNfcStatus {
        NO_NFC,
        NFC_DISABLED,
        NFC_ENABLED
    }

    public static DeviceNfcStatus deviceNfcStatus(Context context) {
        NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context);

        if (!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_NFC) || nfcAdapter == null) {
            return DeviceNfcStatus.NO_NFC;
        }

        if (!nfcAdapter.isEnabled()) {
            return DeviceNfcStatus.NFC_DISABLED;
        }

        return DeviceNfcStatus.NFC_ENABLED;
    }

    public static File writeToInternalFile(Context context, Consumer<OutputStreamWriter> block) throws IOException {
        File file = new File(context.getApplicationContext().getNoBackupFilesDir(),
                System.currentTimeMillis() + ".log");
        OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file));
        try {
            block.accept(writer);
        } finally {
            writer.close();
        }
        return file;
    }
}
