package be.iminds.ilabt.jfed.ui.javafx.probe_gui.command_arguments;

import be.iminds.ilabt.jfed.util.RFC3339Util;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TextField;

import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.ResourceBundle;

/**
 * StringArgumentChooser
 */
public class DateArgumentChooser extends CommandArgumentChooser<String> implements Initializable {
    @FXML
    private TextField valueField;
    @FXML
    private Parent editDateBox;
    @FXML
    private TextField minuteField;
    @FXML
    private TextField hourField;
    @FXML
    private TextField dayField;
    @FXML
    private CheckBox editManuallyCheckBox;

    public DateArgumentChooser() {
        String defaultValue = RFC3339Util.dateToRFC3339String(
                new Date(System.currentTimeMillis() + (2 * 60 * 60 * 1000L)),
                true, true, true);

        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("DateArgumentChooser.fxml"));
        fxmlLoader.setRoot(this);
        fxmlLoader.setController(this);

        try {
            fxmlLoader.load();
            if (defaultValue != null)
                valueField.setText(defaultValue);

            editDateBox.managedProperty().bind(editDateBox.visibleProperty());
            editDateBox.visibleProperty().bind(editManuallyCheckBox.selectedProperty().not());
            valueField.editableProperty().bind(editManuallyCheckBox.selectedProperty());
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }

        changeDate();
    }

    public void changeDate() {
        try {
            int m = minuteField.getText().trim().isEmpty() ? 0 : Integer.parseInt(minuteField.getText().trim());
            int h = hourField.getText().trim().isEmpty() ?   0 : Integer.parseInt(hourField.getText().trim());
            int d = dayField.getText().trim().isEmpty() ?    0 : Integer.parseInt(dayField.getText().trim());

            long date = System.currentTimeMillis();
            date += m * (1000L * 60);
            date += h * (1000L * 60 * 60);
            date += d * (1000L * 60 * 60 * 24);
            String newValue = RFC3339Util.dateToRFC3339String(new Date(date), true, true, true);
            valueField.setText(newValue);
        } catch (NumberFormatException e) {
            //ignore
        }
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        value = valueField.textProperty();
    }
}
