import math
from controller import Robot

PICK_XY = [0.25, 0.1] 
PLACE_XY = [0.1, 0.25]
LIFT_HEIGHT = 0.035
DROP_HEIGHT = -0.035

L1 = 0.2
L2 = 0.2

def calculate_ik(x, y):
    d_squared = x**2 + y**2
    d = math.sqrt(d_squared)

    if d > (L1 + L2) or d < abs(L1 - L2):
        print(f"Target ({x}, {y}) out of reach!")
        return 0, 0

    cos_theta2 = (d_squared - L1**2 - L2**2) / (2 * L1 * L2)
    theta2 = math.acos(cos_theta2)

    alpha = math.atan2(y, x)
    beta = math.atan2(L2 * math.sin(theta2), L1 + L2 * math.cos(theta2))
    theta1 = alpha - beta

    return theta1, theta2

def wait(robot, timestep, seconds):
    steps = int((seconds * 1000) / timestep)
    for _ in range(steps):
        robot.step(timestep)

def run_robot():
    robot = Robot()
    timestep = int(robot.getBasicTimeStep())

    m1 = robot.getDevice('motor1')
    m2 = robot.getDevice('motor2')
    elevator = robot.getDevice('elevator_motor')
    gripper = robot.getDevice('vacuum_gripper')
    
    gripper.enablePresence(timestep)

    p1_m1, p1_m2 = calculate_ik(PICK_XY[0], PICK_XY[1])
    p2_m1, p2_m2 = calculate_ik(PLACE_XY[0], PLACE_XY[1])

    elevator.setPosition(LIFT_HEIGHT)
    m1.setPosition(p1_m1)
    m2.setPosition(p1_m2)
    wait(robot, timestep, 2.0)

    elevator.setPosition(DROP_HEIGHT)
    wait(robot, timestep, 2.0)

    gripper.turnOn()
    wait(robot, timestep, 1.0)

    elevator.setPosition(LIFT_HEIGHT)
    wait(robot, timestep, 2.0)

    m1.setPosition(p2_m1)
    m2.setPosition(p2_m2)
    wait(robot, timestep, 2.0)

    elevator.setPosition(DROP_HEIGHT)
    wait(robot, timestep, 2.0)

    gripper.turnOff()
    wait(robot, timestep, 1.0)

    elevator.setPosition(LIFT_HEIGHT)
    m1.setPosition(0)
    m2.setPosition(0)
    wait(robot, timestep, 2.0)

if __name__ == "__main__":
    run_robot()