package gen2wave.rp70biodemo.tools;

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

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Method;

public class Utils {

    public static boolean checkNfcPowerStatus(Context context) {
        NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context);
        boolean enabled = false;

        if (nfcAdapter != null) {
            enabled = nfcAdapter.isEnabled();
        }

        return enabled;
    }

    public static boolean powerNfc(boolean onoff, Context context) {
        boolean success = false;
        NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context);

        if (nfcAdapter != null) {
            Class<?> NfcManagerClass;
            Method setNfcEnabled;
            try {
                NfcManagerClass = Class.forName(nfcAdapter.getClass().getName());
                setNfcEnabled = NfcManagerClass.getDeclaredMethod(onoff
                        ? "enable" : "disable");
                setNfcEnabled.setAccessible(true);
                success = (Boolean) setNfcEnabled.invoke(nfcAdapter);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return success;
    }

    public static String exec(String command) {
        Process p;
        String result = "";
        try {
            p = Runtime.getRuntime().exec(command);
            BufferedReader bro = new BufferedReader
                    (new InputStreamReader(p.getInputStream()));
            String res;
            while ((res = bro.readLine()) != null) {
                if (result.length() != 0)
                    result += "\n";
                result += res;
            }
            bro.close();
            p.waitFor();
        } catch (Exception err) {
            err.printStackTrace();
            return null;
        }
        int ret = p.exitValue();
        // Log.v(TAG, "ret : "+ret+" ("+result+")");
        return result;
    }
}
