package xyz.veronie.bgg.result; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; import javax.annotation.PostConstruct; import javax.inject.Singleton; import org.eclipse.e4.core.di.annotations.Creatable; import xyz.veronie.bgg.localdb.LocalDbAdapterService; @Creatable @Singleton public class ThingProvider { private LocalDbAdapterService localDbAdapterService; /// list of things. Each ID is expected to exist exactly once. private List things; public ThingProvider() {} @PostConstruct public void init() { localDbAdapterService = new LocalDbAdapterService(); things = new ArrayList(); } /// replace current list with new list public void replaceThings(ArrayList things) { this.things = things; } /// add things from argument to current list iff their ID does not exist yet public void addThings(ArrayList things) { for(Thing tmd : things) { Boolean exists = false; for(Thing thisThing : this.things) { if(tmd.getId() == thisThing.getId()) { exists = true; } } if(!exists) { this.things.add(tmd); } } } // helper function for subtractThingMetas private static Predicate thingEqual(final Thing other) { return p -> p.equals(other); } /// remove the things in the argument from the current list of things (using their ID) public void subtractThings(ArrayList things) { for(Thing thing : things) { this.things.removeIf(thingEqual(thing)); } } /// keep only things that are new in the argument vs the internal thing list public void keepOnlyNew(ArrayList things) { List newThings = new ArrayList(); for(Thing thing : things) { if(!this.things.contains(thing)) { newThings.add(thing); } } this.things = newThings; } /// keep only things that exist in both argument list and current list (by ID) public void intersectThings(ArrayList things) { List cpThings = new ArrayList(this.things); this.things.clear(); for(Thing thing : things) { for(Thing thisThing : cpThings) { if(thing.getId() == thisThing.getId()) { this.things.add(thing); } } } } /// store current list in DB public void storeList(String listName) throws SQLException { localDbAdapterService.storeThingList(this.things, listName); } public void loadList(String name) throws SQLException { // TODO: handle unsaved current list this.things = localDbAdapterService.loadThingList(name); } /// store things as a new list public void importList(List importThings, String listName) { if(importThings != null && !importThings.isEmpty()) { this.things = importThings; } } public int numberOfThings() { return things.size(); } // return the current list of ids public List getThings() { return things; } public List getThingListNames() throws SQLException { return localDbAdapterService.loadThingListNames(); } }