package ch.zhaw.gartenverwaltung;

import ch.zhaw.gartenverwaltung.types.Crop;
import ch.zhaw.gartenverwaltung.types.Task;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.DateCell;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.util.Callback;

import java.net.URL;
import java.time.LocalDate;
import java.util.ResourceBundle;

public class TaskFormularController implements Initializable {
    private Crop crop;

    @FXML
    private TextArea description_area;

    @FXML
    private DatePicker end_datePicker;

    @FXML
    private TextField interval_field;

    @FXML
    private DatePicker start_datePicker;

    @FXML
    private TextField taskName_field;


    public Task returnResult() {
        Task task = new Task(taskName_field.getText(), description_area.getText(),
                start_datePicker.getValue(), end_datePicker.getValue(),
                Integer.parseInt(interval_field.getText()), crop.getCropId().get());
        return task;
    }

    public void setCorp(Crop crop) {
        this.crop = crop;
    }

    public void setTaskValue(Task task) {
        taskName_field.setText(task.getName());
        description_area.setText(task.getDescription());
        start_datePicker.setValue(task.getStartDate());
        end_datePicker.setValue(task.getEndDate().orElse(null));
        if(task.getInterval().orElse(null)!=null) {
            interval_field.setText(task.getInterval().get().toString());
        } else {
            interval_field.setText(null);
        }
    }

    private Callback<DatePicker, DateCell> getDayCellFactory() {

        return (datePicker) -> new DateCell() {
            private final LocalDate today = LocalDate.now();

            @Override
            public void updateItem(LocalDate item, boolean empty) {
                super.updateItem(item, empty);
                setDisable(true);
                setStyle("-fx-background-color: #ffc0cb;");

                if (item.compareTo(today) > 0 && item.compareTo(crop.getStartDate()) > 0) {
                    setDisable(false);
                    setStyle("-fx-background-color: #32CD32;");
                }
            }
        };
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        start_datePicker.setDayCellFactory(getDayCellFactory());
        start_datePicker.setEditable(false);

        end_datePicker.setDayCellFactory(getDayCellFactory());
        end_datePicker.setEditable(false);
    }
}
