import javafx.animation.KeyFrame;
import javafx.animation.PathTransition;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Line;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
// Solution with one instance of Timeline and one instance of PathTransition
public class Parte_c2 extends Application {
    private Ball ball;
    private Timeline timeline;
    private double x,y;
    PathTransition pt;

    @Override // Override the start method in the Application class
    public void start(Stage primaryStage) {
        Scanner posFile= openPositions(primaryStage);
        x=posFile.nextDouble();
        y=posFile.nextDouble();
        ball = new Ball(x, y);
        Pane pane = new Pane();
        pane.getChildren().add(ball);
        Scene scene = new Scene(pane, 1000, 700);
        primaryStage.setTitle("Program Parte C"); // Set the window title
        primaryStage.setScene(scene); // Place the scene in the window
        primaryStage.show();
        pt = new PathTransition();
        pt.setDuration(Duration.millis(950));
        pt.setNode(ball);
        timeline = new Timeline(new KeyFrame(Duration.seconds(1), e -> processPositions(posFile)));
        timeline.setCycleCount(Timeline.INDEFINITE);
        timeline.play();
    }
    private Scanner openPositions(Stage stage) {
        Scanner configFile;
        do {
            try {
                File file = fileChooser(stage);
                configFile = new Scanner(file);
            } catch (FileNotFoundException e) {
                configFile=null;
            }
        } while (configFile ==null);
        return configFile;
    }
    private File fileChooser(Stage stage) {
        FileChooser fChooser = new FileChooser();
        return fChooser.showOpenDialog(stage);
    }
    private void processPositions(Scanner posFile) {
        if (posFile.hasNextDouble()) {
            double lastx = x;
            double lasty = y;
            x = posFile.nextDouble();
            y = posFile.nextDouble();
            pt.setPath(new Line(lastx, lasty, x, y));
            pt.play();
        }
        else
            System.exit(0);
    }
}