package controllers;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import model.*;

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

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

    @FXML
    ListView<Stop> stopsList;
    @FXML
    ListView<Stop> routeList;
    @FXML
    TextField routeName;
    ObservableList<Stop> stops;
    ObservableList<Stop> routeStops;

    public void addStop(){
        ObservableList<Stop> selected = FXCollections.observableArrayList(stopsList.getSelectionModel().getSelectedItems());
        if(selected.size() > 0){
            for (Stop stop: selected){
                stops.remove(stop);
                routeStops.add(stop);
            }
        }
    }

    public void removeStop(){
        ObservableList<Stop> selected = FXCollections.observableArrayList(routeList.getSelectionModel().getSelectedItems());
        if(selected.size() > 0){
            for (Stop stop: selected){
                stops.add(stop);
                routeStops.remove(stop);
            }
        }
    }

    public void addRoute() throws Exception {
        Route route = new Route(routeName.getText(), routeStops);
        if (parent.getSession().getDataManager().addRoute(route)){
            //alert
            Optional<ButtonType> result = popUp(Alert.AlertType.CONFIRMATION, "Success!", "Route has been added.", "Would you like to add another route?", ButtonSets.YesNo);
            if (result.get() == ButtonTypes.No){
                changeScene(SceneCode.MY_ROUTES);
            } else{
                stops = FXCollections.observableArrayList(parent.getSession().getDataManager().getStops());
                routeStops = FXCollections.observableArrayList();
            }
        } else {
            popUp(Alert.AlertType.WARNING, "Warning!", "Duplicate Route", "You may have a route with the same name or same stops.");
        }
    }

    @Override
    public void runLater(){
        stops = FXCollections.observableArrayList(parent.getSession().getDataManager().getStops());
        routeStops = FXCollections.observableArrayList();
        stopsList.setItems(stops);
        routeList.setItems(routeStops);
        stopsList.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
        routeList.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {

    }
}
