package ch.zhaw.gartenverwaltung;

import ch.zhaw.gartenverwaltung.bootstrap.AfterInject;
import ch.zhaw.gartenverwaltung.bootstrap.AppLoader;
import ch.zhaw.gartenverwaltung.bootstrap.ChangeViewEvent;
import ch.zhaw.gartenverwaltung.bootstrap.Inject;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;

import java.io.IOException;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Controller class for the MainFXML.fxml file
 */
public class MainFXMLController {
    private static final Logger LOG = Logger.getLogger(MainFXMLController.class.getName());

    @Inject
    AppLoader appLoader;

    @FXML
    private Button home_button;

    @FXML
    private AnchorPane mainPane;

    @FXML
    private Button myGarden_button;

    @FXML
    private Button mySchedule_button;

    @FXML
    private Button settings_button;

    @FXML
    private Button tutorial_button;

    private final Stage tutorialModal = new Stage();


    /**
     * go to home pane
     */
    @FXML
    void goToHome() {
        showPaneAsMainView("Home.fxml");
        styleChangeButton(home_button);
    }

    /**
     * go to my garden pane
     */
    @FXML
    void goToMyPlants() {
        showPaneAsMainView("MyGarden.fxml");
        styleChangeButton(myGarden_button);
    }

    /**
     * go to the schedule pane
     */
    @FXML
    void goToMySchedule() {
        showPaneAsMainView("MySchedule.fxml");
        styleChangeButton(mySchedule_button);
    }

    /**
     * open dialog of the settings
     * @throws IOException exception
     */
    @FXML
    public void openSettings() throws IOException {
        Dialog<ButtonType> dialog = new Dialog<>();
        dialog.setTitle("Settings");
        dialog.setHeaderText("Settings");
        dialog.setResizable(false);

        DialogPane dialogPane = dialog.getDialogPane();

        dialogPane.getStylesheets().add(
                Objects.requireNonNull(getClass().getResource("bootstrap/dialogStyle.css")).toExternalForm());
        dialogPane.getStyleClass().add("myDialog");

        ButtonType saveSettings = new ButtonType("Save", ButtonBar.ButtonData.OK_DONE);
        dialogPane.getButtonTypes().addAll(saveSettings, ButtonType.CANCEL);

        if (appLoader.loadPaneToDialog("Settings.fxml", dialogPane) instanceof SettingsController controller) {

            dialog.showAndWait()
                    .ifPresent(button -> {
                        if (button.equals(saveSettings)) {
                            controller.saveSettings();
                        }
                    });
        }
    }

    /**
     * Show the tutorial window
     */
    public void showTutorial() {
        if (!tutorialModal.isShowing()) {
            if (tutorialModal.getScene() == null) {
                try {
                    appLoader.loadSceneToStage("Tutorial.fxml", tutorialModal);
                    tutorialModal.initModality(Modality.NONE);
                    tutorialModal.setResizable(false);
                    tutorialModal.sizeToScene();
                } catch (IOException e) {
                    LOG.log(Level.SEVERE, "Could not load Tutorial");
                }
            }
            tutorialModal.show();
        }
        tutorialModal.requestFocus();
    }

    /**
     * Updates the mainPane with the selected fxml file.
     * set HGrow and VGrow to parent AnchorPane.
     * Sends MainController to other Controllers.
     * @param fxmlFile string of fxml file
     */
    public void showPaneAsMainView(String fxmlFile) {
        try {
            Pane anchorPane = appLoader.loadPane(fxmlFile);
            mainPane.getChildren().setAll(anchorPane);
            anchorPane.prefWidthProperty().bind(mainPane.widthProperty());
            anchorPane.prefHeightProperty().bind(mainPane.heightProperty());

            anchorPane.removeEventHandler(ChangeViewEvent.CHANGE_MAIN_VIEW, changeMainViewHandler);
            anchorPane.addEventHandler(ChangeViewEvent.CHANGE_MAIN_VIEW, changeMainViewHandler);
        } catch (IOException e) {
            LOG.log(Level.SEVERE, "Could not load pane.", e);
        }
    }

    private final EventHandler<ChangeViewEvent> changeMainViewHandler = (ChangeViewEvent event) -> showPaneAsMainView(event.view());

    /**
     * preload all menu bar panes
     * @throws IOException exception
     */
    private void preloadPanes() throws IOException {
        appLoader.loadAndCacheFxml("MyGarden.fxml");
        appLoader.loadAndCacheFxml("MySchedule.fxml");
        appLoader.loadAndCacheFxml("Plants.fxml");
    }

    private void styleChangeButton(Button button) {
        /*home_button.setStyle("-fx-background-color: rgb(0,128,0)");
        myGarden_button.setStyle("-fx-background-color: rgb(0,128,0)");
        mySchedule_button.setStyle("-fx-background-color: rgb(0,128,0)");
        settings_button.setStyle("-fx-background-color: rgb(0,128,0)");
        tutorial_button.setStyle("-fx-background-color: rgb(0,128,0)");
        button.setStyle("-fx-background-color: darkgreen");*/
    }

    /**
     * loads the default FXML File
     * {@inheritDoc}
     */
    @AfterInject
    @SuppressWarnings("unused")
    public void init() {
        try {
            preloadPanes();
            showPaneAsMainView("MyGarden.fxml");
            styleChangeButton(myGarden_button);
        } catch (IOException e) {
            LOG.log(Level.SEVERE, "Failed to load FXML-Pane!", e);
        }
        mainPane.getScene().getWindow().setOnCloseRequest(this::closeWindowHandler);
        setIconToButton(home_button, "homeIcon.png");
        setIconToButton(settings_button, "settingsIcon.png");
        tutorial_button.visibleProperty().bind(Settings.getInstance().getShowTutorialProperty());
    }

    /**
     * close Tutorial Window
     * @param windowEvent event
     */
    private void closeWindowHandler(WindowEvent windowEvent) {
        tutorialModal.close();
    }

    /**
     * adds icon to given button
     * @param button the button which get the icon
     * @param iconFileName file name of icon
     */
    private void setIconToButton(Button button, String iconFileName) {
        Image img = new Image(String.valueOf(getClass().getResource("icons/" + iconFileName)));
        ImageView imageView = new ImageView(img);
        imageView.setFitHeight(20);
        imageView.setPreserveRatio(true);
        button.setGraphic(imageView);
    }
}
