package leigh.notek.store;

import org.apache.lucene.queryparser.classic.ParseException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ZettelContext {
    private final ZettelStore store;
    private final ZettelIndex index;
    private String filter;
    private ArrayList<String> ids = new ArrayList<>();

    public ZettelContext(ZettelStore store) throws IOException {
        this.store = store;
        index = new ZettelIndex();
        index.load(store);
        store.getIds(ids);
    }

    public String getFilter() {
        return filter;
    }

    public void getIds(List<String> dst) {
        dst.addAll(ids);
    }

    public void setFilter(String filter) throws ParseException, IOException {
        this.filter = filter;
        if (filter != null) {
            ids.clear();
            index.search(ids, filter);
        } else {
            ids.clear();
            store.getIds(ids);
        }
    }

    public void setZettel(String id, String content) throws IOException {
        store.setZettel(id, content);
        index.update(store, id);
    }

    public String newId() throws IOException {
        String id = store.newId();
        index.update(store, id);
        return id;
    }

    public void delId(String id) throws IOException {
        store.delId(id);
        index.remove(store, id);
        ids.remove(id);
    }

    public ZettelStore getStore() {
        return store;
    }

    public ZettelIndex getIndex() {
        return index;
    }
}
