package com.ttstd.controlled.activity.connection;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.ttstd.controlled.R;
import com.ttstd.controlled.service.ScreenCaptureService;

/**
 * 远程连接请求确认弹窗（Dialog 主题 Activity）。
 * 由 {@link ScreenCaptureService#handleOffer} 在被控端收到 OFFER 时启动，
 * 用户可选择「接受」或「拒绝」。若 60 秒内无操作，则视为拒绝以释放待处理状态。
 */
public class ConnectionRequestActivity extends AppCompatActivity {

    private static final String TAG = "ConnectionRequest";

    /** 启动本 Activity 时携带的发起方（控制端）设备 ID。 */
    public static final String EXTRA_CONTROLLER_ID = "controller_id";

    /** 启动本 Activity 时携带的鉴权类型（NONE=免密连接 / CODE / PASSWORD）。 */
    public static final String EXTRA_AUTH_TYPE = "auth_type";

    /** 无响应自动拒绝的超时时间（毫秒）。 */
    private static final long AUTO_REJECT_TIMEOUT = 60_000L;

    private AlertDialog dialog;
    private final Handler timeoutHandler = new Handler(Looper.getMainLooper());
    private boolean finished = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String controllerId = getIntent() != null
                ? getIntent().getStringExtra(EXTRA_CONTROLLER_ID)
                : null;
        String authType = getIntent() != null
                ? getIntent().getStringExtra(EXTRA_AUTH_TYPE) : null;

        // 服务实例不存在或缺少必要参数时，直接结束，不做任何连接处理。
        if (ScreenCaptureService.getInstance() == null || controllerId == null) {
            Log.w(TAG, "Service not ready or controllerId missing, finishing dialog");
            finish();
            return;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.connection_request_title);

        // 免密连接时在提示中标注，便于用户知晓无需验证码/密码
        String message = getString(R.string.connection_request_message, controllerId);
        if ("NONE".equalsIgnoreCase(authType)) {
            message += "\n\n" + getString(R.string.connection_request_mode_none);
        }
        builder.setMessage(message);
        builder.setCancelable(false);

        builder.setPositiveButton(R.string.connection_accept, (d, which) -> onAccept());
        builder.setNegativeButton(R.string.connection_reject, (d, which) -> onReject());

        dialog = builder.create();
        dialog.setOnDismissListener(d -> {
            // 对话框因任何原因关闭（按钮点击或超时触发）时，确保移除定时任务。
            timeoutHandler.removeCallbacksAndMessages(null);
            finishIfNeeded();
        });
        dialog.show();

        // 启动自动拒绝倒计时。
        timeoutHandler.postDelayed(this::onTimeout, AUTO_REJECT_TIMEOUT);
    }

    private void onAccept() {
        if (finished) return;
        Log.i(TAG, "User accepted connection request");
        ScreenCaptureService service = ScreenCaptureService.getInstance();
        if (service != null) {
            service.acceptConnection();
        }
        finished = true;
    }

    private void onReject() {
        if (finished) return;
        Log.i(TAG, "User rejected connection request");
        ScreenCaptureService service = ScreenCaptureService.getInstance();
        if (service != null) {
            service.rejectConnection();
        }
        finished = true;
    }

    private void onTimeout() {
        if (finished) return;
        Log.i(TAG, "Connection request timed out, auto rejecting");
        ScreenCaptureService service = ScreenCaptureService.getInstance();
        if (service != null) {
            service.rejectConnection();
        }
        finished = true;
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    private void finishIfNeeded() {
        if (!isFinishing() && !isDestroyed()) {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timeoutHandler.removeCallbacksAndMessages(null);
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }
}
