package controllers;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import model.Stop;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Gondr on 1/06/2017.
 */
public class SearchStopsController extends Controller {

    @FXML
    ListView<Stop> stopsList;
    @FXML
    TextField stopAddress;
    @FXML
    TextField stopSuburb;

    private List<Stop> listOfAllStops;
    private ObservableList<Stop> shownStops;

    public void search(){
        shownStops.remove(0, shownStops.size());
        Pattern addressPattern = Pattern.compile(".*", Pattern.CASE_INSENSITIVE);
        if (stopAddress.getText() != "" && stopAddress.getText() != null){
            addressPattern = Pattern.compile(".*"+stopAddress.getText()+".*", Pattern.CASE_INSENSITIVE);
        }
        for (Stop stop:listOfAllStops){
            if (addressPattern.matcher(stop.getAddress()).matches()){
                shownStops.add(stop);
            }
        }
    }

    @Override
    public void runLater() {
        listOfAllStops = new ArrayList<>(parent.getSession().getDataManager().getStops());
        shownStops = FXCollections.observableArrayList(listOfAllStops);
        stopsList.setItems(shownStops);
        stopAddress.textProperty().addListener(e->{
            search();
        });
    }

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

    }
}
