package com.ht.ui.monitor;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.scene.control.TableView;
import javafx.scene.layout.Region;
import javafx.util.Callback;

import org.javafxdata.control.cell.TextFieldCellFactory;

import com.ht.data.RealTimeDataManager;
import com.ht.tags.model.tag.TagVar;
import com.ht.ui.property.SimpleBeanStringProperty;

class TagVarRealTimeDataTable extends TableView<TagVar> {

//	private ObservableList<TagVar> tagVarTableDataList = FXCollections.observableArrayList();
	private Map<TagVar, StringProperty> valuePropertyMap = new HashMap<TagVar, StringProperty>();
	
	private TableColumn<TagVar, String> valueCol;
//	private TableColumn<TagVar, String> acquisitionCol;
	
	@SuppressWarnings("unchecked")
	public TagVarRealTimeDataTable() {
		
		setEditable(true);
		setMaxHeight(Double.MAX_VALUE);
		getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
		setPlaceholder(new Label("未配置变量"));
		
//		setItems(tagVarTableDataList);
		
		TableColumn<TagVar, String> nodeCol = createTagVarTableColumn("变量路径",
				"tagPath", 300);
		TableColumn<TagVar, String> nameCol = createTagVarTableColumn("变量名称",
				"name", 100);
		TableColumn<TagVar, String> typeCol = createTagVarTableColumn("类型", "type", 100);
		TableColumn<TagVar, String> varIdCol = createTagVarTableColumn("变量编号",
				"varId", 150);
		valueCol = createTagVarTableColumn("变量值", "value", 100);
		valueCol.setEditable(true);
		valueCol.setCellFactory(TextFieldCellFactory.<TagVar>forTableColumn());
//		valueCol.setCellFactory( new Callback<TableColumn<TagVar,String>, TableCell<TagVar, String>>() {
//            @Override public TableCell<TagVar, String> call(TableColumn<TagVar, String> list) {
//                return new TagVarValueTableCell();
//            }
//        });

		getColumns().addAll(nodeCol, nameCol, typeCol, varIdCol, valueCol);
		
	}
	
	private TableColumn<TagVar, String> createTagVarTableColumn(
			String colTitle, final String propertyName, double width) {
		TableColumn<TagVar, String> col = new TableColumn<TagVar, String>(
				colTitle);
		col.setPrefWidth(width);
		col.setEditable(false);
		// col.setCellValueFactory(new PropertyValueFactory<TagVar, String>(
		// propertyName));
		col.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<TagVar, String>, ObservableValue<String>>() {

			@Override
			public ObservableValue<String> call(
					CellDataFeatures<TagVar, String> param) {
//				if (propertyName.equals("acquisition")) {
//					return new SimpleStringProperty(
//							param.getValue().isManual() ? "人工采集" : "自动采集");
//				} else 
				if (propertyName.equals("value")) {
					StringProperty p = valuePropertyMap.get(param.getValue());
					if (p == null) {
						Object obj = RealTimeDataManager.INSTANCE.getVarValue(param.getValue().getVarId());
						p = new SimpleStringProperty(getValueString(obj));
						valuePropertyMap.put(param.getValue(), p);
					}

					return p;

				} else {

					return new SimpleBeanStringProperty(param.getValue(),
							propertyName);
				}
			}

			@Override
			protected void finalize() throws Throwable {
				super.finalize();
			}
		});

		return col;
	}
	
	private DecimalFormat df = new DecimalFormat("0.####");
	
	void varDataValueChanged(TagVar var, Object value) {
		String text = getValueString(value);
		
		if (valuePropertyMap.containsKey(var)) {
			valuePropertyMap.get(var).setValue(text);
		}
	}

	private String getValueString(Object value) {
		if (value == null) {
			return "";
		}
		String text = "";
		if (value instanceof Boolean) {
			text = ((Boolean)value) ? "1" : "0";
		} else if (value instanceof Number) {
			text = df.format(((Number) value).doubleValue());
		} else {
			text = value.toString();
		}
		return text;
	}
	
	public static class TagVarValueTableCell extends TableCell<TagVar, String> {
		private RegionLabel region = new RegionLabel();
		
		public TagVarValueTableCell() {
				setGraphic(region);
				setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
		}
		
		@Override
		protected void updateItem(String item, boolean empty) {
			super.updateItem(item, empty);
			if (item != null && !empty) {
				
				TagVar var = getTableView().getItems().get(getIndex());
				region.setText(item);
				if (var.getType().startsWith("遥信") || var.getType().startsWith("遥控")) {
					if (item.equals("1")) {
						region.setStyle("-fx-background-color: red;");
					} else {
						region.setStyle("-fx-background-color: green;");
					}
				}
			}
		}
		
		private class RegionLabel extends Region {
			
			private Label label = new Label();
			
			{
				label.setText("");
				label.setAlignment(Pos.CENTER);
				setAlignment(Pos.CENTER_RIGHT);
				getChildren().add(label);
				
			}
			
			
			private void setText(String value) {
				label.setText(value);
			}
		}
	}
	
}
