package com.sudoxnym.resumd;

import android.accessibilityservice.AccessibilityService;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.KeyEvent;
import android.view.accessibility.AccessibilityEvent;

public class ResumdAccessibilityService extends AccessibilityService {
    private static final String TAG = "ResumdAccessibility";
    private static final String PREFS_NAME = "resumd_prefs";
    
    private Handler handler = new Handler(Looper.getMainLooper());
    private long lastKeyTime = 0;
    private boolean waitingForDouble = false;
    private int lastKeyCode = 0;
    
    private static final long DOUBLE_TAP_TIMEOUT = 400; // ms
    private static final long HOLD_DURATION = 600; // ms
    
    private Runnable holdRunnable;
    private boolean keyHeld = false;

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        // Not used, we only care about key events
    }

    @Override
    public void onInterrupt() {
        Log.d(TAG, "Service interrupted");
    }

    @Override
    protected boolean onKeyEvent(KeyEvent event) {
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        int triggerKey = prefs.getInt("trigger_key", KeyEvent.KEYCODE_BACK);
        String triggerType = prefs.getString("trigger_type", "hold");
        
        if (event.getKeyCode() != triggerKey) {
            return super.onKeyEvent(event);
        }
        
        if (triggerType.equals("double")) {
            return handleDoubleTap(event);
        } else {
            return handleHold(event);
        }
    }
    
    private boolean handleDoubleTap(KeyEvent event) {
        if (event.getAction() != KeyEvent.ACTION_DOWN) {
            return false;
        }
        
        long now = System.currentTimeMillis();
        
        if (waitingForDouble && (now - lastKeyTime) < DOUBLE_TAP_TIMEOUT) {
            // Double tap detected
            waitingForDouble = false;
            handler.removeCallbacksAndMessages(null);
            launchResumd();
            return true;
        }
        
        // First tap - wait for second
        waitingForDouble = true;
        lastKeyTime = now;
        
        handler.postDelayed(() -> {
            waitingForDouble = false;
        }, DOUBLE_TAP_TIMEOUT);
        
        return false; // Let first tap through
    }
    
    private boolean handleHold(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
            keyHeld = false;
            holdRunnable = () -> {
                keyHeld = true;
                launchResumd();
            };
            handler.postDelayed(holdRunnable, HOLD_DURATION);
            return false;
        } else if (event.getAction() == KeyEvent.ACTION_UP) {
            handler.removeCallbacks(holdRunnable);
            if (keyHeld) {
                keyHeld = false;
                return true; // Consume the key up since we handled the hold
            }
            return false;
        }
        return false;
    }
    
    private void launchResumd() {
        Log.d(TAG, "Launching resumd");
        Intent intent = new Intent(this, ResumdActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    @Override
    public void onServiceConnected() {
        super.onServiceConnected();
        Log.d(TAG, "Accessibility service connected");
    }
}
