package com.leviathanstudio.mineide.init;

import javafx.application.Preloader;
import javafx.application.Preloader.StateChangeNotification.Type;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

import com.jfoenix.controls.JFXProgressBar;
import com.leviathanstudio.mineide.util.Constant;

public class MineIDEPreloader extends Preloader
{
    private Stage          preloaderStage;

    private Pane           splashLayout;
    private JFXProgressBar loadProgressPhase;

    @Override
    public void start(final Stage primaryStage) throws Exception
    {

        this.preloaderStage = primaryStage;

        final ImageView splash = new ImageView(new Image(Constant.IMG_DIR + "banner.png"));

        this.loadProgressPhase = new JFXProgressBar();
        this.loadProgressPhase.setPrefWidth(Constant.SPLASH_WIDTH);

        this.splashLayout = new VBox();
        this.splashLayout.getChildren().addAll(splash, this.loadProgressPhase);

        this.splashLayout.setStyle("-fx-padding: 5; " + "-fx-background-color: gainsboro; " + "-fx-border-width:2; "
                + "-fx-border-color: " + "linear-gradient(" + "to bottom, " + "MediumSeaGreen, "
                + "derive(MediumSeaGreen, 50%)" + ");");
        this.splashLayout.setEffect(new DropShadow());

        final Scene splashScene = new Scene(this.splashLayout, Color.TRANSPARENT);
        final Rectangle2D bounds = Screen.getPrimary().getBounds();

        primaryStage.setScene(splashScene);
        primaryStage.setX(bounds.getMinX() + bounds.getWidth() / 2 - Constant.SPLASH_WIDTH / 2);
        primaryStage.setY(bounds.getMinY() + bounds.getHeight() / 2 - Constant.SPLASH_HEIGHT / 2);
        primaryStage.getIcons().add(new Image(Constant.IMG_DIR + "icon.png"));
        primaryStage.setTitle(Constant.APP_NAME);

        primaryStage.initStyle(StageStyle.UNDECORATED);
        primaryStage.setAlwaysOnTop(true);
        primaryStage.show();

    }

    @Override
    public void handleStateChangeNotification(final StateChangeNotification stateChangeNotification)
    {
        if (stateChangeNotification.getType() == Type.BEFORE_START)
            this.preloaderStage.hide();
    }

}