package GUI;

import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.geometry.HPos;
import javafx.geometry.VPos;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import model.SOMConfig;
import model.SOMEvent;
import model.SOMImage;
import model.SOMLayout;
import workers.ScaleWorker;

import java.util.List;

/**
 * Created by Simon on 13.06.2016.
 */
public class GalleryCtl {
    @FXML
    private Pane pane;
    @FXML
    private GridPane grid;
    @FXML
    private Button forthButton;
    @FXML
    private Button backButton;
    @FXML
    private Button pictureButton;
    @FXML
    private ImageView galleryImageView1;
    @FXML
    private ImageView galleryImageView2;
    @FXML
    private ImageView galleryImageView3;
    @FXML
    private ImageView galleryImageView4;
    @FXML
    private ImageView galleryImageView5;
    @FXML
    private ImageView galleryImageView6;
    @FXML
    private ImageView galleryImageView7;
    @FXML
    private ImageView galleryImageView8;
    @FXML
    private ImageView galleryImageView9;
    @FXML
    private Button galleryButton1;
    @FXML
    private Button galleryButton2;
    @FXML
    private Button galleryButton3;
    @FXML
    private Button galleryButton4;
    @FXML
    private Button galleryButton5;
    @FXML
    private Button galleryButton6;
    @FXML
    private Button galleryButton7;
    @FXML
    private Button galleryButton8;
    @FXML
    private Button galleryButton9;

    private ImageView[] imageViews;
    private Button[] imageButtons;
    private int page = 0;
    private SOMImage[] somPageImagesArray = new SOMImage[9];

    public void initialize() {
        setPane();
        setGrid();
        setBackButton();
        setForthButton();
        setPictureButton();

        imageViews = new ImageView[]{
                galleryImageView1,
                galleryImageView2,
                galleryImageView3,
                galleryImageView4,
                galleryImageView5,
                galleryImageView6,
                galleryImageView7,
                galleryImageView8,
                galleryImageView9
        };
        imageButtons = new Button[]{
                galleryButton1,
                galleryButton2,
                galleryButton3,
                galleryButton4,
                galleryButton5,
                galleryButton6,
                galleryButton7,
                galleryButton8,
                galleryButton9
        };

        setImageViews();
        getGalleryImages();
        setImageButtons();
    }

    private void setImageButtons() {
        int i = 0;
        for (Button imageButton : imageButtons) {
            imageButton.setText(null);
            imageButton.setBackground(SOMLayout.BLACK_BG);

            final int finalI = i;
            imageButton.setOnMouseReleased(new EventHandler<MouseEvent>() {

                public void handle(MouseEvent event) {
                    if (!somPageImagesArray[finalI].isPrvthere()) {
                        ScaleWorker.scale(somPageImagesArray[finalI], ScaleWorker.PREVIEW);
                    }
                    SOMGUI.pictureCtl.image.setImage(new Image(somPageImagesArray[finalI].getPrv().toURI().toString()));
                    SOMGUI.captureCtl.image.setImage(new Image(somPageImagesArray[finalI].getPrv().toURI().toString()));
                    SOMGUI.changetopicture();
                }
            });

            i++;
        }
    }

    private void setImageViews() {
        for (ImageView imageView : imageViews) {
            // Set the image aspect ratio to be preserved
            imageView.setPreserveRatio(true);

            // Set the image to the image View
            // TODO ist this ever used?
            imageView.setImage(SOMLayout.LOGO_IMAGE);

            // make it fit the height of the Screen
            imageView.setFitHeight(SOMLayout.screenHeight / 3);
            imageView.setFitWidth(SOMLayout.screenWidth / 4);

            // position the images in Center
            GridPane.setValignment(imageView, VPos.CENTER);
            GridPane.setHalignment(imageView, HPos.CENTER);
        }
    }

    public void setPane() {
        pane.setPrefSize(SOMLayout.screenWidth, SOMLayout.screenHeight);
        pane.setMinSize(SOMLayout.screenWidth, SOMLayout.screenHeight);
        pane.setBackground(SOMLayout.BLACK_BG);
    }

    public void setGrid() {
        grid.setPrefHeight(SOMLayout.screenHeight);
        grid.setPrefWidth(SOMLayout.screenWidth);
        grid.setMinSize(SOMLayout.screenWidth, SOMLayout.screenHeight);


    }

    public void setForthButton() {
        // get the button height & width
        int height = (SOMLayout.screenHeight / 4);
        // set alignment
        GridPane.setHalignment(forthButton, HPos.CENTER);
        GridPane.setValignment(forthButton, VPos.CENTER);
        // set the Button height & width
        forthButton.setPrefSize(height, height);

        // Make it a circle
        forthButton.setBackground(SOMLayout.getTransparentBG10rounded(height / 2));

        //Set Text Color
        forthButton.setTextFill(SOMLayout.WHITE);
        forthButton.setText(null);

        // Set Image
        ImageView imageView = new ImageView(SOMLayout.FORTH_IMAGE);

        forthButton.setGraphic(imageView);

        // Set Mouse Press Action
        forthButton.setOnMousePressed(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent event) {
                // Feedback
                forthButton.setBackground(SOMLayout.getTransparentBG20rounded(SOMLayout.screenHeight / 4));
            }
        });

        // Set Mouse Release Action
        forthButton.setOnMouseReleased(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent event) {

                // Feedback
                forthButton.setBackground(SOMLayout.getTransparentBG10rounded(SOMLayout.screenHeight / 4));

                // Action
                action();
            }

            // Action Performed
            private void action() {
                page++;
                getGalleryImages();
            }
        });
    }

    public void setBackButton() {
        // get the button height & width
        int height = (SOMLayout.screenHeight / 4);
        // set alignment
        GridPane.setHalignment(backButton, HPos.CENTER);
        GridPane.setValignment(backButton, VPos.CENTER);
        // set the Button height & width
        backButton.setPrefSize(height, height);

        // Make it a circle
        backButton.setBackground(SOMLayout.getTransparentBG10rounded(height / 2));

        //Set Text Color
        backButton.setTextFill(SOMLayout.WHITE);
        backButton.setText(null);

        // Set Image
        ImageView imageView = new ImageView(SOMLayout.BACK_IMAGE);

        backButton.setGraphic(imageView);

        // Set Mouse Press Action
        backButton.setOnMousePressed(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent event) {
                // Feedback
                backButton.setBackground(SOMLayout.getTransparentBG20rounded(SOMLayout.screenHeight / 4));
            }
        });

        // Set Mouse Release Action
        backButton.setOnMouseReleased(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent event) {

                // Feedback
                backButton.setBackground(SOMLayout.getTransparentBG10rounded(SOMLayout.screenHeight / 4));

                // Action
                action();
            }

            // Action Performed
            private void action() {
                page--;
                getGalleryImages();
            }
        });
    }

    public void setPictureButton() {
        // get the button height & width
        int height = (SOMLayout.screenHeight / 4);
        // set alignment
        GridPane.setHalignment(pictureButton, HPos.CENTER);
        GridPane.setValignment(pictureButton, VPos.CENTER);
        // set the Button height & width
        pictureButton.setPrefSize(height, height);

        // Make it a circle
        pictureButton.setBackground(SOMLayout.getTransparentBG10rounded(height / 2));

        //Set Text Color
        pictureButton.setTextFill(SOMLayout.WHITE);
        pictureButton.setText(null);

        // Set Image
        ImageView imageView = new ImageView(SOMLayout.PICTURE_IMAGE);

        pictureButton.setGraphic(imageView);

        // Set Mouse Press Action
        pictureButton.setOnMousePressed(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent event) {
                // Feedback
                pictureButton.setBackground(SOMLayout.getTransparentBG20rounded(SOMLayout.screenHeight / 4));
            }
        });

        // Set Mouse Release Action
        pictureButton.setOnMouseReleased(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent event) {

                // Feedback
                pictureButton.setBackground(SOMLayout.getTransparentBG10rounded(SOMLayout.screenHeight / 4));

                // Action
                action();
            }

            // Action Performed
            private void action() {
                SOMGUI.changetopicture();
            }
        });
    }

    public void setGalleryImageView1(ImageView galleryImageView1) {
        this.galleryImageView1 = galleryImageView1;
    }
    
    /*
    * LOGIC
    * -----------------------------------------------------------------------
    * -----------------------------------------------------------------------
    * */

    void getGalleryImages() {
        //Behandelt
        System.out.println("Galerie baut auf");

        // get the Images as Array
        List<SOMImage> imagelist = SOMEvent.getInstance().getImages();
        SOMImage[] imagearray = imagelist.toArray(
                new SOMImage[imagelist.size()]
        );
        // Open new Array for reversing
        SOMImage[] reverseImageArray = new SOMImage[imagelist.size()];
        // Reverse the Array
        for (int h = 0; h < imagearray.length; h++) {
            reverseImageArray[reverseImageArray.length - h - 1] = imagearray[h];
        }

        // get the number of images
        double numberOfPictures = reverseImageArray.length;
        // calculate the number of pages (round up)
        int numberOfPages = (int) Math.ceil(numberOfPictures / SOMConfig.IMAGES_PER_PAGE);

        //report to console
        System.out.println(
                "WE HAVE "
                        + numberOfPages
                        + " PAGES AND "
                        + reverseImageArray.length
                        + " IMAGES"
        );

        // Loop through the Array
        System.out.println("Start looping through current pages images");

        // Loop through the ImageViews of the current page
        for (int i = 0; i < SOMConfig.IMAGES_PER_PAGE; i++) {

            // SYSOUT for manual checking
            System.out.println("Page: " + page);
            System.out.println("Image of Page: " + (i + 1));
            System.out.println("Image of whole; " + (i + (page * SOMConfig.IMAGES_PER_PAGE) + 1));

            // If there is an Image to set at the Position
            // (on the last page it probably stops somewhere in between)
            if (i + (page * SOMConfig.IMAGES_PER_PAGE) < reverseImageArray.length) {

                // get the current image for the position
                SOMImage currentSOMImage = reverseImageArray[i + (page * SOMConfig.IMAGES_PER_PAGE)];
                // Calculate the scaled Image
                currentSOMImage = ScaleWorker.scale(currentSOMImage, ScaleWorker.THUMBNAIL);

                // REPORT THE Images Path to Console
                System.out.println(currentSOMImage.getTmb().toURI().toString());
                // set the image to corresponding ImageView
                imageViews[i].setImage(new Image(currentSOMImage.getTmb().toURI().toString()));

                // save the SOMImage to an Array in the
                // same order for Button Actions etc.
                somPageImagesArray[i] = currentSOMImage;
            }
            // if there are no more images to set
            else {
                // Set the image to null
                imageViews[i].setImage(null);

                // save the SOMImage to an Array in the
                // same order for Button Actions etc.
                somPageImagesArray[i] = null;
            }
        }

        // EN/DISABLE BUTTONS AT THE ENDS
        if (page >= numberOfPages - 1) {

            forthButton.setDisable(true);
        } else {
            forthButton.setDisable(false);
        }

        if (page <= 0) {
            backButton.setDisable(true);
        } else {
            backButton.setDisable(false);
        }
        setImageButtons();
    }

    // Set the Gallery Page Number
    public void setPage(int pageNumber) {
        this.page = pageNumber;
    }

    // Default to 0
    public void setPage() {
        setPage(0);
    }
}
