package com.knecon.fforesight.service.layoutparser.processor.docstrum.service;

import java.util.List;

import org.springframework.stereotype.Service;
import org.tinspin.index.Index;
import org.tinspin.index.kdtree.KDTree;

import com.knecon.fforesight.service.layoutparser.processor.docstrum.model.Character;
import com.knecon.fforesight.service.layoutparser.processor.docstrum.model.Neighbor;

@Service
public class NearestNeighbourService {

    private static final int NUMBER_OF_NEIGHBOURS = 8;


    public void findNearestNeighbors(List<Character> characters) {
        KDTree<Character> kdTree = KDTree.create(2);
        characters.forEach(c -> kdTree.insert(new double[]{c.getX(), c.getY()}, c));

        for(Character c : characters) {
            Index.PointIteratorKnn<Character> iterator = kdTree.queryKnn(new double[]{c.getX(), c.getY()}, NUMBER_OF_NEIGHBOURS + 1);
            // skip the first as this is identity
            if(iterator.hasNext()) {
                iterator.next();
            }
            while(iterator.hasNext()) {
                c.getNeighbors().add(new Neighbor(iterator.next().value(), c));
            }
        }

    }

}

