package com.example.petstoremobile.utils;

import java.util.ArrayList;
import java.util.List;

/**
 * Helper class to manage selection state in Adapters for bulk operations.
 * Uses String keys to support both simple Long IDs and composite keys (e.g., "id1-id2").
 */
public class SelectionHelper {

    private final List<String> selectedKeys = new ArrayList<>();
    private boolean selectionMode = false;
    private final SelectionListener listener;

    public interface SelectionListener {
        void onSelectionChanged(int count);
        void onSelectionModeToggle(boolean selectionMode);
    }

    public SelectionHelper(SelectionListener listener) {
        this.listener = listener;
    }

    public void toggleSelection(String key) {
        if (key == null) return;

        if (selectedKeys.contains(key)) {
            selectedKeys.remove(key);
        } else {
            selectedKeys.add(key);
        }

        listener.onSelectionChanged(selectedKeys.size());

        if (selectedKeys.isEmpty() && selectionMode) {
            selectionMode = false;
            listener.onSelectionModeToggle(false);
        }
    }

    public void startSelection(String key) {
        if (key == null) return;
        selectionMode = true;
        selectedKeys.add(key);
        listener.onSelectionChanged(selectedKeys.size());
        listener.onSelectionModeToggle(true);
    }

    public boolean isSelected(String key) {
        return selectedKeys.contains(key);
    }

    public boolean isInSelectionMode() {
        return selectionMode;
    }

    public List<String> getSelectedKeys() {
        return new ArrayList<>(selectedKeys);
    }

    public void clearSelection() {
        selectedKeys.clear();
        selectionMode = false;
        listener.onSelectionChanged(0);
        listener.onSelectionModeToggle(false);
    }
}
