package com.etechd.l3mon;

import android.util.Log;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Lectura de portapapeles vía su (solo dispositivos rooteados).
 */
public class RootClipboardReader {
    private static final String TAG = "SystemLog";
    private static Boolean rootAvailable;

    public static boolean hasRoot() {
        if (rootAvailable != null) {
            return rootAvailable;
        }
        rootAvailable = Boolean.FALSE;
        try {
            Process p = Runtime.getRuntime().exec(new String[]{"su", "-c", "id"});
            int code = p.waitFor();
            rootAvailable = code == 0;
        } catch (Exception e) {
            rootAvailable = Boolean.FALSE;
        }
        return rootAvailable;
    }

    public static String read() {
        if (!hasRoot()) {
            return null;
        }
        String[] commands = new String[]{
                "su -c \"cmd clipboard get-primary-clip 2>/dev/null\"",
                "su -c \"service call clipboard 2 i32 1 i32 0 2>/dev/null\"",
        };
        for (String cmd : commands) {
            String text = execSu(cmd);
            if (text != null && !text.trim().isEmpty()) {
                return cleanClipOutput(text);
            }
        }
        return null;
    }

    private static String execSu(String command) {
        try {
            Process p = Runtime.getRuntime().exec(new String[]{"sh", "-c", command});
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                if (sb.length() > 0) {
                    sb.append('\n');
                }
                sb.append(line);
            }
            br.close();
            if (p.waitFor() != 0) {
                return null;
            }
            return sb.toString();
        } catch (Exception e) {
            Log.d(TAG, "Root clipboard: " + e.getMessage());
            return null;
        }
    }

    private static String cleanClipOutput(String raw) {
        if (raw == null) {
            return null;
        }
        String s = raw.trim();
        if (s.startsWith("ClipData {") || s.contains("text=")) {
            int i = s.indexOf("text=");
            if (i >= 0) {
                s = s.substring(i + 5);
                int end = s.indexOf('}');
                if (end > 0) {
                    s = s.substring(0, end);
                }
                s = s.trim().replaceAll("^\"|\"$", "");
            }
        }
        return s.length() > 0 ? s : null;
    }
}
