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

import java.awt.geom.Line2D;
import java.awt.geom.Point2D;

import com.knecon.fforesight.service.layoutparser.processor.model.table.Ruling;

import lombok.experimental.UtilityClass;

@UtilityClass
public final class RulingTextDirAdjustUtil {

    /**
     * Converts a ruling (line of a table) the same way TextPositions are converted in PDFBox.
     * This will get the y position of the text, adjusted so that 0,0 is upper left and it is adjusted based on the text direction.
     * <p>
     * See org.apache.pdfbox.text.TextPosition
     */
    public Line2D.Float convertToDirAdj(Ruling ruling, float dir, float pageWidth, float pageHeight) {

        return new Line2D.Float(convertPoint(ruling.x1, ruling.y1, dir, pageWidth, pageHeight), convertPoint(ruling.x2, ruling.y2, dir, pageWidth, pageHeight));
    }


    private Point2D convertPoint(float x, float y, float dir, float pageWidth, float pageHeight) {

        var xAdj = getXRot(x, y, dir, pageWidth, pageHeight);
        var yLowerLeftRot = getYLowerLeftRot(x, y, dir, pageWidth, pageHeight);
        var yAdj = dir == 0 || dir == 180 ? pageHeight - yLowerLeftRot : pageWidth - yLowerLeftRot;
        return new Point2D.Float(xAdj, yAdj);
    }


    @SuppressWarnings("SuspiciousNameCombination")
    private float getXRot(float x, float y, float dir, float pageWidth, float pageHeight) {

        if (dir == 0) {
            return x;
        } else if (dir == 90) {
            return y;
        } else if (dir == 180) {
            return pageWidth - x;
        } else if (dir == 270) {
            return pageHeight - y;
        }
        return 0;
    }


    private float getYLowerLeftRot(float x, float y, float dir, float pageWidth, float pageHeight) {

        if (dir == 0) {
            return y;
        } else if (dir == 90) {
            return pageWidth - x;
        } else if (dir == 180) {
            return pageHeight - y;
        } else if (dir == 270) {
            return x;
        }
        return 0;
    }

}
