package View;

import Model.Sensor;
import Model.VirtualSensor;
import javafx.beans.property.ListProperty;
import javafx.beans.property.*;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.FXCollections;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.TextArea;
import javafx.fxml.FXML;
import javafx.util.converter.NumberStringConverter;


import java.io.IOException;
import java.util.ArrayList;


public class VirtualSensorController extends FXMLWindow{

    @FXML
    private ListView<Sensor> SensorList;
    @FXML
    private TextArea temp;
    @FXML
    private TextArea vTemp;
    private Sensor sensor;

    public VirtualSensorController(VirtualSensor v,String url,String title) throws IOException{
        super(url,title);
        this.sensor = v;
        ListProperty<Sensor> sensors = new SimpleListProperty<>(FXCollections.observableList(new ArrayList<>(v.getSensors().values())));
        SensorList.itemsProperty().bind(sensors);
        vTemp.textProperty().bindBidirectional(v.temperatureProperty(),new NumberStringConverter());
    }

    public void initialize(){
        SensorList.setCellFactory((param) ->
                new ListCell<>(){
                    @Override
                    protected void updateItem(Sensor item, boolean empty){
                        super.updateItem(item,empty);
                        if(!empty){
                            textProperty().bind(item.temperatureProperty().asString());
                        }else {
                            textProperty().unbind();
                            setText("");
                        }
                    }
                });
        SensorList.getSelectionModel().selectedItemProperty().addListener((__,old,newV)->{
            if (old != null) {
                temp.textProperty().unbindBidirectional(old.temperatureProperty());
            }
            if(newV != null){
                temp.textProperty().bindBidirectional((Property<String>)newV.temperatureProperty().asString());
            }
        });
    }
}
