package ui;

import controller.Controller;
import controller.SettingsController;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollBar;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;

import java.io.File;

public class SettingsWindow {

	@FXML
	private CheckBox holeCheckBox;
	@FXML
	private ScrollBar touchscreenSlider;
	@FXML
	private Label touchscreenLabel;
	@FXML
	private ScrollBar fingerSlider;
	@FXML
	private Label fingerLabel;
	@FXML
	private Button scadPath;

	private static SettingsWindow window;
	private Stage stage;

	public SettingsWindow() {
		window = this;
	}

	static SettingsWindow getWindow() {
		return window;
	}

	void setUpListener() {
		holeCheckBox.setSelected(Controller.getC().getFill());
		touchscreenSlider.setValue(Controller.getC().getSizeScreen() * 10);
		touchscreenScrolled();
		fingerSlider.setValue(Controller.getC().getSizeFinger() * 10);
		fingerScrolled();
		scadPath.setText(Controller.getC().getOpenSCADPath().toString());

		touchscreenSlider.valueProperty().addListener((observable, oldValue, newValue) -> touchscreenScrolled());
		fingerSlider.valueProperty().addListener((observable, oldValue, newValue) -> fingerScrolled());
	}

	@FXML
	protected void fillHoleChecked() {
		Controller.getC().setFill(holeCheckBox.isSelected());
	}

	@FXML
	private void touchscreenScrolled() {
		Controller.getC().setSizeScreen(Math.round(touchscreenSlider.getValue())/10f);
		touchscreenLabel.setText("Conductive dot diameter touchscreen: "+ Math.round(touchscreenSlider.getValue())/10f+"mm");
	}

	@FXML
	private void fingerScrolled() {
		Controller.getC().setSizeFinger(Math.round(fingerSlider.getValue())/10f);
		fingerLabel.setText("Conductive dot diameter finger: "+ Math.round(fingerSlider.getValue())/10f +"mm");
	}

	@FXML
	protected void pathClicked() {
		Task task = new Task() {
			@Override
			protected Void call() {
				DirectoryChooser chooser = new DirectoryChooser();
				Platform.runLater(() -> {
							File file = chooser.showDialog(stage);

							if (file != null) {
								Controller.getC().setOpenSCADPath(file.toPath());
								Platform.runLater(() -> scadPath.setText(file.toPath().toString()));
							}
						});
				return null;
			}
		};
		new Thread(task).start();
	}

	@FXML
	protected void saveClicked() {
		SettingsController.saveSettings();
		stage.close();
	}

	@FXML
	protected void cancelSettings() {
		File file = new File(Main.olipPath + "settings.ini");
		if (file.exists())
			SettingsController.loadSettings();
		stage.close();
	}

	void setStage(Stage stage) {
		this.stage = stage;
	}
}
