import javafx.geometry.Insets;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.scene.shape.Rectangle;

/** Esta clase permite cambiar los fondos de pantalla, donde la dirección de cada imagen se encuentra en un array
 */
public class BackgroundCarousel {
    private BorderPane pane;
    private int backnum=1;
    private String[] imgs;

    /**
     * Constructor de BackgroundCarousel
     * @param p BorderPane del cual se manipula su fondo de pantalla
     */
    public BackgroundCarousel(BorderPane p){
        pane = p;

        imgs = new String[]{"/background/background5.gif",
                            "/background/background7.gif",
                            "/background/interior.jpg",
                            "/background/lakehouse.jpg",
                            "/background/corner.gif"};


        pane.setStyle("-fx-background-image: url('" + imgs[0] + "');");
        pane.getStyleClass().add("backgrounds");


        ImageView iconRight = new ImageView(new Image("/icons/right-arrow.png"));
        iconRight.setPickOnBounds(true);


        ImageView iconLeft = new ImageView(new Image("/icons/right-arrow.png"));
        iconLeft.setRotate(180);
        iconLeft.setPickOnBounds(true);

        iconRight.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> {
            right();
        });

        iconLeft.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> {
            left();
        });

        HBox hb = new HBox();
        hb.setPrefWidth(100);

        Region region1 = new Region();
        HBox.setHgrow(region1, Priority.ALWAYS);

        hb.getChildren().addAll(iconLeft, region1, iconRight);

        pane.setBottom(hb);

        Rectangle rect = new Rectangle();
        pane.setPadding(new Insets(10));
        pane.setCenter(rect);
    }

    /**
     * Event Listener para cambair el fondo de pantalla con las flechas del teclado
     * @param e Evento KeyEvent.KEY_PRESSED
     */
    public void changeBackground(KeyEvent e){
        if(e.getCode().equals(KeyCode.LEFT)){
            left();
        } else if (e.getCode().equals(KeyCode.RIGHT)) {
            right();
        }
    }

    /**
     * Método para cambiar al fondo de pantalla a la izquierda del índice actual
     */
    private void left(){
        if(backnum <= 0){
            backnum = imgs.length - 1;
        } else {
            backnum--;
        }
        pane.setStyle("-fx-background-image: url('" + imgs[backnum] + "');");
    }

    /**
     * Método para cambiar al fondo de pantalla a la derecha del índice actual
     */
    private void right(){
        if(backnum >= (imgs.length - 1)){
            backnum=0;
        }else{
            backnum++;
        }
        pane.setStyle("-fx-background-image: url('" + imgs[backnum] + "');");
    }

}
