package com.ttstd.adbloopback;

import com.ttstd.adbloopback.adb.AdbConnection;
import com.ttstd.adbloopback.adb.AdbKeyPair;
import com.ttstd.adbloopback.adb.AdbPairing;
import com.ttstd.adbloopback.adb.AdbStream;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

/**
 * ADB 管理器：封装密钥持久化、配对、连接及 Shell 指令执行。
 * 它是上层 UI 与底层 ADB 协议库之间的桥梁。
 */
public class AdbManager {
    private final File privateKeyFile;
    private final File publicKeyFile;
    private AdbKeyPair keyPair;
    private AdbConnection connection;

    public AdbManager(File filesDir) {
        this.privateKeyFile = new File(filesDir, "adb_private.key");
        this.publicKeyFile = new File(filesDir, "adb_public.key");
        loadOrCreateKeyPair();
    }

    private void loadOrCreateKeyPair() {
        try {
            if (privateKeyFile.exists() && publicKeyFile.exists()) {
                keyPair = AdbKeyPair.read(privateKeyFile, publicKeyFile);
            } else {
                keyPair = AdbKeyPair.generate();
                keyPair.write(privateKeyFile, publicKeyFile);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /** 发起无线调试配对（TLS-PSK） */
    public void pair(int port, String pairingCode) throws Exception {
        AdbPairing.pair("127.0.0.1", port, pairingCode, keyPair);
    }

    /** 连接无线调试主端口 */
    public void connect(int port) throws Exception {
        if (connection != null) {
            try { connection.close(); } catch (Exception ignored) {}
        }
        connection = AdbConnection.connect("127.0.0.1", port, keyPair);
    }

    /** 断开连接 */
    public void disconnect() {
        if (connection != null) {
            try {
                connection.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            connection = null;
        }
    }

    /** 执行 Shell 命令并获取全部输出 */
    public String execShell(String command) throws Exception {
        if (connection == null || !connection.isConnected()) {
            throw new IOException("ADB 未连接");
        }
        AdbStream stream = connection.open("shell:" + command);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] data;
        while ((data = stream.read()) != null) {
            bos.write(data);
        }
        stream.close();
        return bos.toString("UTF-8");
    }

    /** 快速发送点击指令 */
    public void tap(int x, int y) throws Exception {
        execShell("input tap " + x + " " + y);
    }

    public boolean isConnected() {
        return connection != null && connection.isConnected();
    }
}
