package controllers;

import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.util.Callback;
import model.*;

import java.net.URL;
import java.util.Optional;
import java.util.ResourceBundle;

/**
 * Created by Gondr on 5/04/2017.
 */
public class AddTripController extends Controller{

    @FXML
    private ComboBox<Route> routeDropdown;
    @FXML
    private ComboBox<Ride> ride;
    @FXML
    private ComboBox<String> direction;
    @FXML
    private TableView<TripStop> routeTable;
    @FXML
    private TableColumn<TripStop, String> stopName;
    @FXML
    private TableColumn<TripStop, String> stopTime;
    @FXML
    private CheckBox mon;
    @FXML
    private CheckBox tues;
    @FXML
    private CheckBox wed;
    @FXML
    private CheckBox thur;
    @FXML
    private CheckBox fri;
    @FXML
    private CheckBox sat;
    @FXML
    private CheckBox sun;
    @FXML
    private ComboBox<String> reoccur;
    @FXML
    private DatePicker endDate;
    @FXML
    private TextField tripName;

    ObservableList<TripStop> stops;

    @FXML
    private void addTrip() throws Exception {
        boolean[] days = {mon.isSelected(), tues.isSelected(), wed.isSelected(), thur.isSelected(), fri.isSelected(),
                            sat.isSelected(), sun.isSelected()};
        boolean boolReoccur = reoccur.getValue() == "Yes";
        String failure = "";
        boolean fail = false;
        if (stops.size() == 0){
            failure += "You have not selected a route.\n";
            fail = true;
        }
        if (ride.getValue() == null){
            failure += "You must select a ride (vehicle) for this trip.\n";
            fail = true;
        }
        if (tripName.getText() == null || tripName.getText() == ""){
            failure += "You must name this Trip.\n";
            fail = true;
        }

        for (TripStop stop: stops){
            if (stop.getTime().equals("")){
                failure += "You must have all times for stops filled out.\n";
                fail = true;
                break;
            }
        }

        if (!fail) {
            String date = "";
            if (endDate.getValue() != null && boolReoccur == true){
                date = endDate.getValue().toString();
            }
            Trip trip = new Trip(tripName.getText() ,stops, direction.getValue(), ride.getValue(), days, boolReoccur, date);
            System.out.println(trip);
            Optional<ButtonType> result = popUp(Alert.AlertType.CONFIRMATION, "Success!", "Trip Added", String.format("Your Trip %1s has been added successfully!\n\nWould you like to add another trip?", tripName.getText()), ButtonSets.YesNo);
            parent.getSession().getDataManager().addTrip(trip);
            if (result.get() == ButtonTypes.No){
                changeScene(SceneCode.MY_TRIPS);
            } else{
                changeScene(SceneCode.ADD_TRIP);
            }
        }else{
            popUp(Alert.AlertType.WARNING, "Warning!", "Crucial Information missing", failure);
        }
    }

    @Override
    public void runLater(){
        routeDropdown.setItems(parent.getSession().getDataManager().getRoutes());
        ride.setItems(parent.getSession().getDataManager().getRides());
        stopName.setCellValueFactory(p -> p.getValue().nameProperty());
        stopTime.setCellFactory(TextFieldTableCell.forTableColumn());
        stopTime.setOnEditCommit(
                new EventHandler<CellEditEvent<TripStop, String>>() {
                    @Override
                    public void handle(CellEditEvent<TripStop, String> t) {
                        ((TripStop) t.getTableView().getItems().get(
                                t.getTablePosition().getRow())
                        ).setTime(t.getNewValue());
                    }
                }
        );
        routeDropdown.valueProperty().addListener(new ChangeListener<Route>() {
            @Override
            public void changed(ObservableValue<? extends Route> observable, Route oldValue, Route newValue) {
                for (Stop stop: newValue.getStops()){
                    stops.add(new TripStop(stop.getAddress(), ""));
                }
                routeTable.setItems(stops);
            }
        });
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        String[] reoccurence = {"Yes","No"};
        ObservableList<String> reoccurs = FXCollections.observableArrayList(reoccurence);
        reoccur.setItems(reoccurs);
        reoccur.getSelectionModel().select(1);
        reoccur.valueProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue == "Yes"){
                endDate.setDisable(false);
            }else{
                endDate.setDisable(true);
            }
        });

        String[] dir = {Trip.TO_UNI, Trip.TO_HOME};
        ObservableList<String> dirArr = FXCollections.observableArrayList(dir);
        direction.setItems(dirArr);
        direction.getSelectionModel().selectFirst();

        stops = FXCollections.observableArrayList();

        routeTable.setEditable(true);
        stopName.setEditable(false);
        stopTime.setEditable(true);

        endDate.setDisable(true);
    }
}
