package com.ttstd.adbloopback;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.textfield.TextInputEditText;

public class MainActivity extends AppCompatActivity {

    private AdbManager adbManager;

    private TextInputEditText etPairPort;
    private TextInputEditText etPairCode;
    private TextInputEditText etMainPort;
    private TextInputEditText etTapX;
    private TextInputEditText etTapY;
    private TextInputEditText etCmd;
    private TextView tvStatus;
    private TextView tvLog;
    private ScrollView scrollLog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        adbManager = new AdbManager(getFilesDir());

        etPairPort = findViewById(R.id.et_pair_port);
        etPairCode = findViewById(R.id.et_pair_code);
        etMainPort = findViewById(R.id.et_main_port);
        etTapX = findViewById(R.id.et_tap_x);
        etTapY = findViewById(R.id.et_tap_y);
        etCmd = findViewById(R.id.et_cmd);
        tvStatus = findViewById(R.id.tv_status);
        tvLog = findViewById(R.id.tv_log);
        scrollLog = findViewById(R.id.scroll_root);

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
            log("⚠️ 当前系统低于 Android 11（API 30），无线调试不可用。");
        }

        findViewById(R.id.btn_open_settings).setOnClickListener(v -> openDeveloperOptions());
        findViewById(R.id.btn_pair).setOnClickListener(v -> doPair());
        findViewById(R.id.btn_connect).setOnClickListener(v -> doConnect());
        findViewById(R.id.btn_disconnect).setOnClickListener(v -> doDisconnect());
        findViewById(R.id.btn_tap).setOnClickListener(v -> doTap());
        findViewById(R.id.btn_exec).setOnClickListener(v -> doExec());
    }

    private void openDeveloperOptions() {
        try {
            startActivity(new Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS));
            Toast.makeText(this, "请开启「无线调试」，并记录配对端口/码与主端口", Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Toast.makeText(this, "无法打开开发者选项，请手动进入", Toast.LENGTH_LONG).show();
        }
    }

    private void doPair() {
        String portStr = etPairPort.getText().toString().trim();
        String code = etPairCode.getText().toString().trim();
        if (portStr.isEmpty() || code.isEmpty()) {
            Toast.makeText(this, "请填写配对端口与配对码", Toast.LENGTH_SHORT).show();
            return;
        }
        int port = Integer.parseInt(portStr);
        runBg("配对", () -> {
            adbManager.pair(port, code);
            log("✅ 配对成功（TLS-PSK 完成，公钥已加入 adbd 授权列表）");
        });
    }

    private void doConnect() {
        String portStr = etMainPort.getText().toString().trim();
        if (portStr.isEmpty()) {
            Toast.makeText(this, "请填写无线调试主端口", Toast.LENGTH_SHORT).show();
            return;
        }
        int port = Integer.parseInt(portStr);
        runBg("连接", () -> {
            adbManager.connect(port);
            log("✅ 已连接无线调试主端口 " + port + "，获得 ADB 权限管道");
            runOnUiThread(() -> tvStatus.setText("状态：已连接（ADB 权限）"));
        });
    }

    private void doDisconnect() {
        runBg("断开", () -> {
            adbManager.disconnect();
            runOnUiThread(() -> tvStatus.setText("状态：未连接"));
            log("🔌 已断开连接");
        });
    }

    private void doTap() {
        String xStr = etTapX.getText().toString().trim();
        String yStr = etTapY.getText().toString().trim();
        if (xStr.isEmpty() || yStr.isEmpty()) {
            Toast.makeText(this, "请填写 X/Y 坐标", Toast.LENGTH_SHORT).show();
            return;
        }
        int x = Integer.parseInt(xStr);
        int y = Integer.parseInt(yStr);
        runBg("input tap", () -> {
            adbManager.tap(x, y);
            log("👆 已发送 input tap " + x + " " + y);
        });
    }

    private void doExec() {
        String cmd = etCmd.getText().toString().trim();
        if (cmd.isEmpty()) {
            Toast.makeText(this, "请输入 shell 命令", Toast.LENGTH_SHORT).show();
            return;
        }
        runBg("exec: " + cmd, () -> {
            String out = adbManager.execShell(cmd);
            log("▶ " + cmd + "\n" + (out.isEmpty() ? "(无输出)" : out));
        });
    }

    private interface ThrowingRunnable {
        void run() throws Exception;
    }

    private void runBg(String name, ThrowingRunnable task) {
        log("⏳ 执行 " + name + " …");
        new Thread(() -> {
            try {
                task.run();
            } catch (Exception e) {
                log("❌ " + name + " 失败：" + e.getMessage());
                e.printStackTrace();
            }
        }).start();
    }

    private void log(String line) {
        runOnUiThread(() -> {
            tvLog.append(line + "\n");
            scrollLog.post(() -> scrollLog.fullScroll(View.FOCUS_DOWN));
        });
    }
}
