package dev.lions.btpxpress.view;

import jakarta.faces.view.ViewScoped;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.List;
import java.util.function.Predicate;

@Getter
@Setter
public abstract class BaseListView<T, ID> implements Serializable {
    
    protected static final Logger LOG = LoggerFactory.getLogger(BaseListView.class);
    private static final long serialVersionUID = 1L;

    protected List<T> items = new java.util.ArrayList<>();
    protected T selectedItem;
    protected boolean loading = false;

    public abstract void loadItems();
    
    protected void applyFilters(List<T> items, List<Predicate<T>> filters) {
        if (filters != null && !filters.isEmpty()) {
            filters.stream()
                .filter(p -> p != null)
                .forEach(filter -> items.removeIf(filter.negate()));
        }
    }

    public void search() {
        LOG.debug("Recherche lancée pour {}", getClass().getSimpleName());
        loadItems();
    }

    public void resetFilters() {
        LOG.debug("Réinitialisation des filtres pour {}", getClass().getSimpleName());
        resetFilterFields();
        loadItems();
    }

    protected abstract void resetFilterFields();

    public String viewDetails(ID id) {
        LOG.debug("Redirection vers détails : {}", id);
        return getDetailsPath() + id + "?faces-redirect=true";
    }

    protected abstract String getDetailsPath();

    public String createNew() {
        LOG.debug("Redirection vers création");
        return getCreatePath() + "?faces-redirect=true";
    }

    protected abstract String getCreatePath();

    public void delete() {
        if (selectedItem != null) {
            LOG.info("Suppression : {}", selectedItem);
            performDelete();
            items.remove(selectedItem);
            selectedItem = null;
        }
    }

    protected abstract void performDelete();
}

