package com.inspect.infrared.selectArea.immp;

import com.inspect.infrared.selectArea.SelectArea;

import java.util.ArrayList;
import java.util.List;

public class LineSelectArea extends SelectArea {
    private int x1;
    private int y1;
    private int x2;
    private int y2;
    private final List<LineSelectArea.Point> points = new ArrayList<>();

    public LineSelectArea(int... coordinates) {
        super(coordinates);
    }

    public boolean isIn(int x, int y) {
        this.convertCoordinate();
        this.checkList();
        return this.points.stream().anyMatch((item) -> item.x == x && item.y == y);
    }

    public void convertCoordinate() {
        if (this.x1 > this.x2) {
            int temp = this.x1;
            this.x1 = this.x2;
            this.x2 = temp;
            temp = this.y1;
            this.y1 = this.y2;
            this.y2 = temp;
        }

    }

    public void checkList() {
        if (this.points.isEmpty()) {
            int x = Math.abs(this.x2 - this.x1);
            int y = Math.abs(this.y2 - this.y1);
            int increment = 1;
            if (this.y1 > this.y2) {
                increment = -1;
            }

            if (x > y) {
                this.checkListOfXMore(x, y, increment);
            } else {
                this.checkListOfYMore(x, y, increment);
            }
        }

    }

    public void checkListOfXMore(int x, int y, int increment) {
        for (int i = this.x1; i < this.x2 + 1; ++i) {
            double cy = ((double) i - (double) this.x1) / (double) x * (double) y + (double) increment;
            this.points.add(new Point(i, (int) cy));
        }

    }

    public void checkListOfYMore(int x, int y, int increment) {
        for (int i = this.y1; i < this.y2 + 1; ++i) {
            double cy = ((double) i - (double) this.y1) / (double) y * (double) x + (double) increment;
            this.points.add(new Point((int) cy, i));
        }

    }

    public static class Point {
        int x;
        int y;

        public Point(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }
}
