package sample;

import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.stage.DirectoryChooser;

import java.io.File;
import java.io.IOException;

public class Controller {


    private Downloader con = new Downloader(this);
    private Launcher launch = new Launcher(this);

    @FXML
    private TextField installLoc;
    @FXML
    private Button launchButton;
    @FXML
    private TabPane tabView;
    @FXML
    private TextArea output;
    @FXML
    private Button patchButton;
    @FXML
    private TextField serverAddress;
    @FXML
    private ProgressBar progressBar;
    @FXML
    private Button openButton;


    @FXML
    private void launchHandle(){

        launchMinecraft();
    }

    private void launchMinecraft() {
        launchButton.setDisable(true);
        launchButton.setText("Launching...");
        Runnable task1 = () -> launch.launchMinecraft(installLoc.getText());
        new Thread(task1).start();
    }

    @FXML
    private void dirHandle(){
        DirectoryChooser chooser = new DirectoryChooser();
        File chosen = new File(installLoc.getText());
        if(chosen.exists()) chooser.setInitialDirectory(new File(installLoc.getText()));

        chooser.setTitle("Choose Minecraft install location");
        File location = chooser.showDialog(installLoc.getScene().getWindow());

        if (location!=null) installLoc.setText(location.getAbsolutePath());
        else System.out.println("Please select a correct location.");
    }

    @FXML
    private void patchHandle(){
        con.patch(installLoc.getText(),serverAddress.getText());
    }

    @FXML
    protected void initialize(){
        //set install location to appdata/.minecraft
        installLoc.setText(System.getenv("Appdata")+"\\.minecraft");
    }

    @FXML
    private void openHandle(){
        try {
            Runtime.getRuntime().exec("explorer.exe \"" + installLoc.getText()+"\"");
        } catch (IOException e) {
            e.printStackTrace();
            printOutput("Cannot open chosen directory.",true);
        }
    }

    void launchFailed() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        printOutput("launcher.jar not found, please install minecraft",true);
        Platform.runLater(()->launchButton.setDisable(false));
        Platform.runLater(()->launchButton.setText("Launch"));
    }

    void printOutput(String value, boolean fancy){
        if (fancy) Platform.runLater(()->output.appendText("=== "+value+" ===\n"));
        else Platform.runLater(()->output.appendText(value+"\n"));
    }

    void updateProgress(double value){
        Platform.runLater(()->progressBar.setProgress(value));
    }
}

@@ -1557,32 +1557,56 @@
  patchHandle()%7B%0A
+        output.clear();%0A
         con.patc

clear output when re-running patcher