package org.academiadecodigo.carcrash.field;

import org.academiadecodigo.carcrash.Utils;

public class Position {
    private static final double ABSOLUTEMAXSPEED = 4.0; // same as stepping one row/col

    private double col;
    private double row;

    public Position() {
        setRandom();
    }

    public Position(int col, int row) {
        this.col = col;
        this.row = row;
    }

    // these need to be ints to be used by lanterna
    public int getCol() {
        return (int) Math.floor(this.col);
    }

    public int getRow() {
        return (int) Math.floor(this.row);
    }

    public void setRandom() {
        this.col = (int) (Math.random() * Field.width);
        this.row = (int) (Math.random() * Field.height);
    }

    public void moveTo(double col, double row) {
        this.col = alias(Math.max(0.0, Math.min(Field.width-1.0, col)));
        this.row = alias(Math.max(0.0, Math.min(Field.height-1.0, row)));
    }

    public void moveTo(int col, int row) {
        moveTo((double) col, (double) row);
    }

    public void moveTo(Position newPosition) {
        this.col = newPosition.getCol();
        this.row = newPosition.getRow();
    }

    public void moveTowards(Position dest, double relativeSpeed) {
        double horizontalSpeedMult = 1;  // car can move at max speed horizontally
        double verticalSpeedMult = 0.5;  // car will move at half speed vertically

        double difW = 0;
        double difH = 0;
        double speed = relativeSpeed/ABSOLUTEMAXSPEED;
        if (col > dest.getCol()) {
            difW -= speed*horizontalSpeedMult;
        } else if (col < dest.getCol()) {
            difW += speed*horizontalSpeedMult;
        } else if (this.row > dest.getRow()) {
            difH -= speed*verticalSpeedMult;
        } else {
            difH += speed*verticalSpeedMult;
        }
//        System.out.println(this + " + " + difW + "," + difH + " -> " + dest);
//        System.out.println(alias(difW));
        moveTo(col + difW, row + difH);
    }

    public double alias(double value) {
        return Math.round(value * ABSOLUTEMAXSPEED) / ABSOLUTEMAXSPEED;
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof Position)) {
            return false;
        }
        Position pos = (Position) obj;
        return this.getRow() == pos.getRow() && this.getCol() == pos.getCol();
    }

    @Override
    public String toString() {
        return "(" + this.getCol() + ", " + this.getRow() + ")";
    }
}
