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

import java.util.List;

import org.springframework.stereotype.Service;

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

@Service
public class SpacingService {

    private static final double SPACING_HISTOGRAM_RESOLUTION = 0.5;
    private static final double SPACING_HISTOGRAM_SMOOTHING_LENGTH = 2.5;
    private static final double SPACING_HIST_SMOOTHING_STANDARD_DEVIATION = 0.5;
    private static final double ANGLE_TOLERANCE = Math.PI / 6;


    public double computeCharacterSpacing(List<Character> characters) {

        return computeSpacing(characters, 0);
    }


    public double computeLineSpacing(List<Character> characters) {

        return computeSpacing(characters, Math.PI / 2);
    }


    private double computeSpacing(List<Character> characters, double angle) {

        double maxDistance = Double.NEGATIVE_INFINITY;

        for (Character character : characters) {
            for (Neighbor neighbor : character.getNeighbors()) {
                maxDistance = Math.max(maxDistance, neighbor.getDistance());
            }
        }
        Histogram histogram = new Histogram(0, maxDistance, SPACING_HISTOGRAM_RESOLUTION);
        AngleFilter angleFilter = new AngleFilter(angle - ANGLE_TOLERANCE, angle + ANGLE_TOLERANCE);
        for (Character character : characters) {
            for (Neighbor neighbor : character.getNeighbors()) {
                if (angleFilter.matches(neighbor)) {
                    histogram.add(neighbor.getDistance());
                }
            }
        }

        histogram.gaussianSmooth(SPACING_HISTOGRAM_SMOOTHING_LENGTH, SPACING_HIST_SMOOTHING_STANDARD_DEVIATION);
        return histogram.getPeakValue();
    }

}
