package com.moviesdb;

import com.sun.javafx.collections.MappingChange;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.geometry.HPos;
import javafx.geometry.Pos;
import javafx.geometry.VPos;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.control.Alert.AlertType;

import com.moviesdb.Movie;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import com.moviesdb.DataBaseConnector;
import javafx.stage.Stage;

import java.time.chrono.AbstractChronology;
import java.util.LinkedHashMap;
import java.util.Map;
//For reading properties from .properties file
import com.moviesdb.ConnectionParams;


public class Controller {
    @FXML
    AnchorPane browserPane;
    @FXML
    MenuItem menuNew;
    @FXML
    FlowPane moviesGrid;
    @FXML
    ScrollPane scrollPane;
    @FXML
    AnchorPane detailsPane;
    @FXML
    TextFlow detailsContent;
    @FXML
    AnchorPane detailsPicPane;
    @FXML
    AnchorPane filterPane;
    @FXML
            Label button;

    @FXML
    Label minimizeButton;
    @FXML
    Label maximizeButton;
    @FXML
    Label closeButton;
    @FXML
            MenuBar menuPane;

    Map<Label, Movie> map;
    Label[] labelsMovies;
    Movie[] movies;
    Movie my_movie;
    DataBaseConnector my_connector;
    ConnectionParams workParams;

    double xOffset;
    double yOffset;

    public void initialize(Stage primaryStage){

        ImageView minimizeImageView = new ImageView(new Image(getClass().getResourceAsStream("media\\minimize.png")));
        minimizeImageView.setFitHeight(16);
        minimizeImageView.setFitWidth(16);
        minimizeButton.setGraphic(minimizeImageView);
        minimizeButton.setOnMouseClicked(e-> {
            primaryStage.setIconified(true);
        });

        ImageView maximizeImageView = new ImageView(new Image(getClass().getResourceAsStream("media\\maximize.png")));
        maximizeImageView.setFitHeight(16);
        maximizeImageView.setFitWidth(16);
        maximizeButton.setGraphic(maximizeImageView);
        maximizeButton.setOnMouseClicked(e-> {
            if (primaryStage.isMaximized() == true)
                primaryStage.setMaximized(false);
            else
                primaryStage.setMaximized(true);
        });

        ImageView CloseImageView = new ImageView(new Image(getClass().getResourceAsStream("media\\cancel.png")));
        CloseImageView.setFitHeight(16);
        CloseImageView.setFitWidth(16);
        closeButton.setGraphic(CloseImageView);
        closeButton.setOnMouseClicked(e-> {
            primaryStage.close();
        });

        menuPane.setOnMousePressed(new EventHandler<javafx.scene.input.MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                xOffset = primaryStage.getX() - event.getScreenX();
                yOffset = primaryStage.getY() - event.getScreenY();
            }
        });

        menuPane.setOnMouseDragged(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                primaryStage.setX(event.getScreenX() + xOffset);
                primaryStage.setY(event.getScreenY() + yOffset);
            }
        });

        //TODO change path to connection.properties
        workParams = new ConnectionParams("src/com/moviesdb/connection.properties");
        if (!workParams.initilized())
            //TODO this is temporaly handler
            System.out.println(workParams.getInitilizeErrCause().toString());
        else {
            my_connector = new DataBaseConnector();
            my_connector.initConnection(workParams);
        }

    }

    public void loadPosters()
    {
        //detailsPane.setMinWidth(300);
        //get movies array
        movies = my_connector.getMovies();
        labelsMovies = new Label[movies.length];

        map = new LinkedHashMap<Label, Movie>();
        //
        for (int i = 0; i < movies.length; i++)
        {
            labelsMovies[i] = new Label();
            ImageView image = new ImageView(movies[i].cover());

            map.put(labelsMovies[i], movies[i]);

            image.setFitHeight(222);
            image.setFitWidth(150);
            labelsMovies[i].setGraphic(image);
            GridPane.setValignment(labelsMovies[i], VPos.CENTER);
            GridPane.setHalignment(labelsMovies[i], HPos.CENTER);
            Label movie = labelsMovies[i];
            labelsMovies[i].setOnMouseClicked(e-> {
                openDetails(movie);
            });
        }
        //moviesGrid.setPrefWidth(scrollPane.getWidth());
        //clear old data in grid
        moviesGrid.getChildren().clear();
        //moviesGrid.setAlignment(Pos.CENTER);
        //fill grid by movies
        //moviesGrid.addRow(0, labelsMovies[0], labelsMovies[1]);
        //moviesGrid.minHeight(moviesGrid.getMinHeight() + 222);
        //moviesGrid.setPrefWidth(browserPane.getWidth()-26);
        //moviesGrid.setMinHeight(scrollPane.getHeight());
        gridResize();
        //moviesGrid.setPrefHeight(moviesGrid.getHeight());


    }

    public void returnMessage()
    {
        Alert alert = new Alert(AlertType.CONFIRMATION, "Are you sure you want to format your system?");
        alert.showAndWait().ifPresent(response -> {
            if (response == ButtonType.OK) {
            }
        });
    }

    public void openDetails(Label e)
    {
        if (detailsPane.getMinWidth() < 1) {
            //detailsInfoPane = new AnchorPane();
            //detailsPicPane.getChildren().clear();

            detailsPane.setMinWidth(300);
            my_movie = map.get(e);
            //my_movie= my_connector.getMovieInfo(1);

            //detailsContent.Text(my_movie.name() + "\n" + my_movie.year() + "\n" + my_movie.duration() + "\n" +  my_movie.genre() + "\n" + my_movie.description());
            Text info = new Text("Name:\n    " + my_movie.name() + "\n" +
                                    "Year: \n    " + my_movie.year() + "\n" +
                                    "Duration: \n    " + my_movie.duration() + "\n" +
                                    "Genre: \n    " + my_movie.genre() + "\n" +
                                    "Description: \n    " + my_movie.description());
            info.setStyle("-fx-font-size: 14; -fx-fill: #9f9f9f;");
            detailsContent.getChildren().clear();
            detailsContent.getChildren().add(info);

            detailsPicPane.getChildren().clear();
            //detailsPane.setMaxWidth(300);
            //Label movie = e;
            ImageView detailsImage = new ImageView();


            ImageView image = new ImageView((my_movie.cover()));
            image.setFitHeight(222);
            image.setFitWidth(150);

            detailsImage = ((ImageView) image);
            detailsImage.setX((detailsPane.getWidth() - detailsImage.getFitWidth()) / 2 + 100);
            detailsImage.setY(0);
            //movie.
            detailsPicPane.getChildren().add(detailsImage);
            // 300px is details window width
            //scrollPane.setPrefWidth(browserPane.getWidth()-300);
            //scrollPane.setPrefHeight(browserPane.getHeight());
            //moviesGrid.setPrefWidth(browserPane.getWidth());
            //moviesGrid.setPrefHeight(browserPane.getHeight());
            //loadPosters();

            gridResize();
            //button.setText(Double.toString(browserPane.getWidth()));

        }
        else
        {
            detailsPicPane.getChildren().clear();
            detailsPane.setMinWidth(0);
            detailsPane.setPrefWidth(0);
            detailsPane.setMaxWidth(0);
            // 300px is details window width
            //scrollPane.setPrefWidth(browserPane.getWidth()+300);
            //scrollPane.setPrefHeight(browserPane.getHeight());
            //moviesGrid.setPrefWidth(scrollPane.getWidth()+300);
            //moviesGrid.setPrefHeight(browserPane.getHeight());
            //browserPane.setPrefWidth(browserPane.getWidth()+300);
            gridResize();
            //button.setText(Double.toString(browserPane.getWidth()));
        }
    }

    public void closeDetails()
    {
        detailsPicPane.getChildren().clear();
        detailsPane.setMinWidth(1);
        detailsPane.setPrefWidth(1);
    }

    public void openFilter()
    {
        if (filterPane.getWidth() < 1)
        {
            //filterPane.maxWidth(300);
            filterPane.setMinWidth(300);
            filterPane.setPrefWidth(300);
            filterPane.setMaxWidth(300);
            //loadPosters();
            // 300px is filter window width
            //scrollPane.setPrefWidth(browserPane.getWidth()-300);
            //scrollPane.setPrefHeight(browserPane.getHeight());
            //moviesGrid.setPrefWidth(browserPane.getWidth() -300);
            //moviesGrid.setPrefHeight(browserPane.getHeight());
            gridResize();
        }
        else
        {
            filterPane.setMinWidth(0);
            filterPane.setPrefWidth(0);
            filterPane.setMaxWidth(0);
            //loadPosters();
            // 300px is filter window width
            //scrollPane.setPrefWidth(browserPane.getWidth()+300);
            //scrollPane.setPrefHeight(browserPane.getHeight());
            //moviesGrid.setPrefWidth(scrollPane.getWidth()+300);
            //moviesGrid.setPrefHeight(browserPane.getHeight());
            gridResize();
        }
    }

    public void gridResize()
    {
        int colsAdd = ((int)scrollPane.getWidth())/200 - 2;
        int cols = colsAdd + 2;

        int rows = movies.length / cols + 1;
        if (242*rows<scrollPane.getHeight())
            moviesGrid.setMinHeight(scrollPane.getHeight());
        else
            moviesGrid.setMinHeight(242*rows);
        moviesGrid.setMaxWidth(scrollPane.getWidth());
        moviesGrid.setPrefWidth(scrollPane.getWidth());

        moviesGrid.setAlignment(Pos.CENTER);
        moviesGrid.setHgap( 75);
        moviesGrid.setVgap( 25);

        moviesGrid.getChildren().clear();
        int k = 0;
        for(int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                try {
                    moviesGrid.getChildren().add(labelsMovies[k]);
                }
                catch (Exception err)
                {
                    k++;
                }
                if(k == movies.length - 1)
                    break;
                k++;
            }
        }
    }


}
