package com.sudoxnym.resumd;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.content.SharedPreferences;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityWindowInfo;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class ResumdService extends AccessibilityService {
    private static final String PREFS_NAME = "resumd_prefs";
    private static final String KEY_RECENTS = "recent_packages";
    private static final String KEY_RUNNING = "running_packages";
    private static final int MAX_RECENTS = 20;
    
    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
            CharSequence packageName = event.getPackageName();
            if (packageName != null) {
                String pkg = packageName.toString();
                // skip system stuff we dont care about
                if (pkg.equals("com.android.systemui")) return;
                if (pkg.equals("com.sudoxnym.resumd")) return;
                if (pkg.equals("com.android.permissioncontroller")) return;
                
                addToRunning(pkg);
                updateRecentOrder(pkg);
            }
        }
        
        updateRunningFromWindows();
    }
    
    private void updateRunningFromWindows() {
        List<AccessibilityWindowInfo> windows = getWindows();
        Set<String> currentWindows = new HashSet<>();
        
        for (AccessibilityWindowInfo window : windows) {
            CharSequence title = window.getTitle();
        }
        
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        String runningStr = prefs.getString(KEY_RUNNING, "");
    }
    
    private void addToRunning(String packageName) {
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        String existing = prefs.getString(KEY_RUNNING, "");
        
        Set<String> running = new HashSet<>();
        if (!existing.isEmpty()) {
            for (String pkg : existing.split(",")) {
                if (!pkg.isEmpty()) running.add(pkg);
            }
        }
        running.add(packageName);
        
        StringBuilder sb = new StringBuilder();
        for (String pkg : running) {
            if (sb.length() > 0) sb.append(",");
            sb.append(pkg);
        }
        prefs.edit().putString(KEY_RUNNING, sb.toString()).apply();
    }
    
    private void updateRecentOrder(String packageName) {
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        String existing = prefs.getString(KEY_RECENTS, "");
        
        LinkedHashSet<String> recents = new LinkedHashSet<>();
        recents.add(packageName);
        
        if (!existing.isEmpty()) {
            for (String pkg : existing.split(",")) {
                if (!pkg.isEmpty() && recents.size() < MAX_RECENTS) {
                    recents.add(pkg);
                }
            }
        }
        
        StringBuilder sb = new StringBuilder();
        for (String pkg : recents) {
            if (sb.length() > 0) sb.append(",");
            sb.append(pkg);
        }
        prefs.edit().putString(KEY_RECENTS, sb.toString()).apply();
    }
    
    public static void removeFromRunning(android.content.Context context, String packageName) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        
        String runningStr = prefs.getString(KEY_RUNNING, "");
        Set<String> running = new HashSet<>();
        for (String pkg : runningStr.split(",")) {
            if (!pkg.isEmpty() && !pkg.equals(packageName)) {
                running.add(pkg);
            }
        }
        StringBuilder sb = new StringBuilder();
        for (String pkg : running) {
            if (sb.length() > 0) sb.append(",");
            sb.append(pkg);
        }
        prefs.edit().putString(KEY_RUNNING, sb.toString()).apply();
        
        String recentsStr = prefs.getString(KEY_RECENTS, "");
        LinkedHashSet<String> recents = new LinkedHashSet<>();
        for (String pkg : recentsStr.split(",")) {
            if (!pkg.isEmpty() && !pkg.equals(packageName)) {
                recents.add(pkg);
            }
        }
        sb = new StringBuilder();
        for (String pkg : recents) {
            if (sb.length() > 0) sb.append(",");
            sb.append(pkg);
        }
        prefs.edit().putString(KEY_RECENTS, sb.toString()).apply();
    }
    
    @Override
    public void onInterrupt() {}
    
    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        AccessibilityServiceInfo info = new AccessibilityServiceInfo();
        info.eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED | 
                          AccessibilityEvent.TYPE_WINDOWS_CHANGED;
        info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
        info.flags = AccessibilityServiceInfo.FLAG_RETRIEVE_INTERACTIVE_WINDOWS;
        setServiceInfo(info);
    }
}
