package com.ttstd.controlled.input;

import android.util.Log;
import java.util.Locale;

/**
 * 通过 Shell 命令（Runtime.exec）执行注入操作的实现类。
 */
public class ShellInputUtils implements InputExecutor {
    private static final String TAG = "ShellInputUtils";

    @Override
    public void injectTap(int x, int y) {
        executeShellCommand(String.format(Locale.US, "input tap %d %d", x, y));
    }

    @Override
    public void injectLongPress(int x, int y) {
        injectSwipe(x, y, x, y, 1000);
    }

    @Override
    public void injectSwipe(int x1, int y1, int x2, int y2, long duration) {
        executeShellCommand(String.format(Locale.US, "input swipe %d %d %d %d %d", x1, y1, x2, y2, duration));
    }

    @Override
    public void injectKeyEvent(int keyCode) {
        executeShellCommand(String.format(Locale.US, "input keyevent %d", keyCode));
    }

    @Override
    public void injectMotionEvent(int action, int x, int y) {
        // Shell 命令不支持高效的连续手势追踪，这里仅作兼容处理
        if (action == 0) { // ACTION_DOWN
            injectTap(x, y);
        }
    }

    private void executeShellCommand(String command) {
        try {
            Log.d(TAG, "Executing shell command: " + command);
            Process process = Runtime.getRuntime().exec(command);
            int exitCode = process.waitFor();
            Log.i(TAG, "Shell command executed with exit code " + exitCode);
        } catch (Exception e) {
            Log.e(TAG, "Error executing shell command: " + command, e);
        }
    }
}
