/*
 * @author Ranides Atterwim <ranides@gmail.com>
 * @copyright Ranides Atterwim
 * @license WTFPL
 * @url http://ranides.net/projects/assira.drafts
 */
package net.ranides.assira.index;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import net.ranides.assira.collection.maps.ASortedMap;
import net.ranides.assira.collection.maps.MultiMap;
import net.ranides.assira.collection.maps.RBTreeMultiMap;
import net.ranides.assira.collection.sets.ASortedSet;
import net.ranides.assira.collection.sets.IdentSet;
import net.ranides.assira.collection.sets.MultiSet;
import net.ranides.assira.collection.sets.RBTreeMultiSet;

import net.ranides.assira.generic.CompareUtils;

/**
 *
 * @author Ranides Atterwim <ranides@gmail.com>
 */
public class IQueryMapTree<V> extends IQueryAbstract.IQMap<V> {
    
    private final Map<String, Comparator> name2sindex = new HashMap<>();
    
    private final Map<String, Function> name2mindex = new HashMap<>();
    
    private final Map<Comparator, RBTreeMultiSet<V>> cindexes = new HashMap<>();
    
    private final Map<Function, RBTreeMultiMap<Object, V>> mindexes = new HashMap<>();

    @Override
    public IQueryMap<V> index(String name, Comparator<V> index) {
        RBTreeMultiSet<V> set = new RBTreeMultiSet<>(index);
        cindexes.put(index, set);
        name2sindex.put(name, index);
        for(V item : values()) {
            set.add(item);
        }
        return this;
    }

    @Override
    public <T> IQueryMap<V> index(String name, Function<V, T> index) {
        RBTreeMultiMap<Object,V> map = new RBTreeMultiMap<>();
        mindexes.put(index, map);
        name2mindex.put(name, index);
        for(V item : values()) {
            map.put(index.apply(item),item);
        }
        return this;
    }

    @Override
    public void remove(V value) {
        for(SortedSet<V> index : cindexes.values()) {
            IQueryMapTree.this.iremove(index, value);
        }
        for(SortedMap<Object,V> index : mindexes.values()) {
            iremove(index, value);
        }
    }
    
    private void iremove(SortedSet<V> set, V value) {
        Comparator<? super V> c = set.comparator();
        Iterator<V> i = set.headSet(value).iterator();
        while(i.hasNext()) {
            V item = i.next();
            if(c.compare(item, value) !=0) {
                return;
            }
            if(CompareUtils.equals(item,value)) {
                i.remove();
                return;
            }
        }
    }
    
    private void iremove(SortedMap<Object,V> map, V value) {
        Comparator<Object> c = CompareUtils.comparator();
        Iterator<Entry<Object,V>> i = map.headMap(value).entrySet().iterator();
        while(i.hasNext()) {
            Entry<Object,V> item = i.next();
            if(c.compare(item.getKey(), value) !=0) {
                return;
            }
            if(CompareUtils.equals(item.getValue(),value)) {
                i.remove();
                return;
            }
        }
    }
    
    @SuppressWarnings("unchecked")
    @Override
    public void updateAll() {
        List<V> items = new ArrayList<>(values());
        for(SortedSet<V> index : cindexes.values()) {
            index.clear();
            index.addAll(items);
        }
        for(Entry<Function, RBTreeMultiMap<Object,V>> entry : mindexes.entrySet()) {
            Function fun = entry.getKey();
            RBTreeMultiMap<Object, V> index = entry.getValue();
            index.clear();
            for(V item : items) {
                index.put(fun.apply(item), item);
            }
        }
    }
    
    @Override
    public IQueryAbstract<V> find() {
        return new TreeQuery();
    }

    @SuppressWarnings("unchecked")
    @Override
    public void put(V value) {
        for(SortedSet<V> index : cindexes.values()) {
            index.add(value);
        }
        for(Entry<Function, RBTreeMultiMap<Object,V>> entry : mindexes.entrySet()) {
            Function fun = entry.getKey();
            RBTreeMultiMap<Object, V> index = entry.getValue();
            index.put(fun.apply(value), value);
        }
    }

    @Override
    public void clear() {
        for(SortedSet<V> index : cindexes.values()) {
            index.clear();
        }
        for(SortedMap<Object,V> index : mindexes.values()) {
            index.clear();
        }
    }
    
    private Collection<V> values() {
        if(cindexes.isEmpty()) {
            return Collections.emptySet();
        }
        return cindexes.values().iterator().next();
    }
    
    private static <T> Collection<T> tail(ASortedMap<Object, T> mi, Object value) {
        Object last = after(mi,value);
        return last==null ? Collections.emptyList() : mi.tailMap(last).values();
    }
    
    private static <T> Collection<T> tail(ASortedSet<T> ci, T value) {
        T last = after(ci,value);
        return last==null ? Collections.emptyList() : ci.tailSet(last);
    }

    private static Object after(ASortedMap<Object, ?> map, Object value) {
        Comparator<Object> cmp = CompareUtils.comparator();
        Iterator<Object> i = map.keySet().iterator(value);
        while(i.hasNext()) {
            Object next = i.next();
            if(cmp.compare(value, next)!=0) {
                return next;
            }
        }
        return null;
    }
    
    private static <T> T after(ASortedSet<T> set, T value) {
        Comparator<? super T> cmp = set.comparator();
        Iterator<T> i = set.iterator(value);
        while(i.hasNext()) {
            T next = i.next();
            if(cmp.compare(value, next)!=0) {
                return next;
            }
        }
        return null;
    }
    
    private static <T> Collection<T> merge(Collection<T> a, Collection<T> b) {
        Collection<T> out = new IdentSet<>(a.size() + b.size());
        out.addAll(a);
        out.addAll(b);
        return out;
    }

    
    private final class TreeQuery extends IQueryAbstract<V> {
        
        private final List<Supplier<Collection<V>>> selectors;
        
        private final boolean require;

        public TreeQuery() {
            this.selectors = Collections.emptyList();
            this.require = true;
        }
        
        public TreeQuery(TreeQuery query, Supplier<Collection<V>> selector) {
            this.selectors = new ArrayList<>(query.selectors.size()+1);
            this.selectors.addAll(query.selectors);
            this.selectors.add(selector);
            this.require = true;
        }
        
        public TreeQuery(TreeQuery query, boolean require) {
            this.selectors = new ArrayList<>(query.selectors);
            this.require = require;
        }
        
        @SuppressWarnings("unchecked")
        @Override
        protected <T> Function<V, T> mindex(String name) {
            return name2mindex.get(name);
        }

        @SuppressWarnings("unchecked")
        @Override
        protected Comparator<V> sindex(String name) {
            return name2sindex.get(name);
        }

        @Override
        public IQuery<V> require() {
            return new TreeQuery(this, true);
        }

        @Override
        public IQuery<V> optional() {
            return new TreeQuery(this, false);
        }

        @Override
        public IQuery<V> eq(Comparator<V> index, V value) {
            RBTreeMultiSet<V> ci = cindexes.get(index);
            return select(ci, () -> ci.getAll(value));
        }

        @Override
        public <T> IQuery<V> eq(Function<V, T> index, T value) {
            RBTreeMultiMap<Object, V> mi = mindexes.get(index);
            return select(mi, () -> mi.getAll(value));
        }

        @Override
        public IQuery<V> gt(Comparator<V> index, V value) {
            RBTreeMultiSet<V> ci = cindexes.get(index);
            return select(ci, () -> tail(ci, value));
        }

        
        @Override
        public <T> IQuery<V> gt(Function<V, T> index, T value) {
            RBTreeMultiMap<Object, V> mi = mindexes.get(index);
            return select(mi, () -> tail(mi, value));
        }

        @Override
        public IQuery<V> lt(Comparator<V> index, V value) {
            RBTreeMultiSet<V> ci = cindexes.get(index);
            return select(ci, () -> ci.headSet(value));
        }

        @Override
        public <T> IQuery<V> lt(Function<V, T> index, T value) {
            RBTreeMultiMap<Object, V> mi = mindexes.get(index);
            return select(mi, () -> mi.headMap(value).values());
        }

        @Override
        public IQuery<V> in(Comparator<V> index, V begin, V end) {
            RBTreeMultiSet<V> ci = cindexes.get(index);
            return select(ci, () -> ci.subSet(begin, end));
        }

        @Override
        public <T> IQuery<V> in(Function<V, T> index, T begin, T end) {
            RBTreeMultiMap<Object, V> mi = mindexes.get(index);
            return select(mi, () -> mi.subMap(begin, end).values());
        }
        
        @Override
        public void update(Consumer<? super V> consumer) {
            select().forEach(v -> IQueryMapTree.this.update(v, consumer));
        }
        
        @Override
        public void remove() {
            removeAll(select());
        }
        
        private <T> IQuery<V> select(MultiSet<V> ci, Supplier<Collection<V>> f) {
            if(require) {
                return new TreeQuery(this, f);
            } else {
                return new TreeQuery(this, () -> merge(f.get(), ci.getAll(null)));
            }
        }

        private <T> IQuery<V> select(MultiMap<Object, V> mi, Supplier<Collection<V>> f) {
            if(require) {
                return new TreeQuery(this, f);
            } else {
                return new TreeQuery(this, () -> merge(f.get(), mi.getAll(null)));
            }
        }
        
        @Override
        protected Collection<V> select() {
            int psize = 0;
            Collection<V> prim = null;
            List<Collection<V>> sec = new ArrayList<>(selectors.size()-1);
            for(Supplier<Collection<V>> s : selectors) {
                Collection<V> c = s.get();
                int csize = c.size();
                
                if(psize > csize) {
                    sec.add(prim);
                    prim = null;
                }
                if(prim==null) {
                    prim = c;
                    psize = csize;
                } else {
                    sec.add(c);
                }
            }
            
            if(prim==null) {
                return Collections.emptyList();
            }
            
            List<V> out = new ArrayList<>(prim.size());
            for(V item : prim) {
                if(selected(sec,item)) {
                    out.add(item);
                }
            }
            return out;
        }
        
        private boolean selected(List<Collection<V>> sec, V item) {
            for(Collection<V> s : sec) {
                if(!s.contains(item)) {
                    return false;
                }
            }
            return true;
        }
        
    }
    
}
