package net.ddns.mahaljsp.brick;


import javafx.scene.media.AudioClip;

import javafx.application.Application;
import javafx.event.Event;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class App extends Application{
    public static AppController c;
    public static Bar bar;
    int speed=40;
    Ball ball;
    public static AudioClip clip;
    public static Brick[][] bricks;
        public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) throws Exception {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("main.fxml"));
        Parent root=loader.load();
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.setTitle("打磚塊");
        stage.show();

        c=loader.getController();
        c.panel.setStyle("-fx-background-color: black;");
        bar = new Bar();
        c.panel.getChildren().add(bar);
        bar.setY(c.panel.getHeight()-bar.getHeight());
        

        stage.setOnCloseRequest(e -> close(e));
        Color[] colors = {Color.RED, Color.ORANGE, Color.YELLOW, Color.GREEN, Color.BLUE};
        bricks = new Brick[5][15];
        for(int i=0; i<5; i++){
            for (int j=0; j<15; j++){
                var brick = new Brick(j*53+3, i*22+80, colors[i]);
                c.panel.getChildren().add(brick);
                bricks[i][j] = brick;
            }
        }
        ball = new Ball();
        c.panel.getChildren().add(ball);     

        scene.setOnKeyPressed(e->keyPress(e));
        scene.setOnMouseMoved(e -> mouseMove(e));
        clip = new AudioClip(
            getClass().getResource("hit3.wav").toString()
        );        

    }
    public void close(Event e){
        ball.close();
        System.out.println("視窗即將關閉");
    }
    public void mouseMove(MouseEvent e){
        bar.setX(e.getX() - bar.getWidth() / 2);
    }
    public void keyPress(KeyEvent e){
        switch (e.getCode()){
            case LEFT -> {
                if (bar.getX()-speed>0)
                    bar.setX(bar.getX()-speed);
                else
                    bar.setX(0);  
                }
            case RIGHT ->{
                if (bar.getX()+bar.getWidth()+speed<c.screen.getWidth())
                    bar.setX(bar.getX()+speed);
                else
                    bar.setX(c.screen.getWidth()-bar.getWidth());      
            }
            default -> {}
        }
    }   
}
