package com.softgraf.vendas.view;

import java.util.List;

import com.softgraf.vendas.model.dao.abstrato.AbstractGenericDAO;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.ObservableList;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;

public class TableViewHelper<G> {

	private AbstractGenericDAO<G> dao;
	private String sqlSelect;
	private TableView<ObservableList<StringProperty>> tableView;

	public TableViewHelper(TableView<ObservableList<StringProperty>> tableView, AbstractGenericDAO<G> dao, String sqlSelect) {
		this.dao = dao;
		this.sqlSelect = sqlSelect;
		this.tableView = tableView;

		Platform.runLater(new Runnable() {
			@Override
			public void run() {
				List<String> listaColunas = dao.listarColunas(sqlSelect + " LIMIT 0");

				for (int i = 0; i < listaColunas.size(); i++) {
					String nome = listaColunas.get(i);
					TableColumn<ObservableList<StringProperty>, String> coluna = new TableColumn<>(nome);
					final int NUMCOL = i;
					coluna.setCellValueFactory(param -> {
						return new SimpleStringProperty(param.getValue().get(NUMCOL).getValue());
					});
					tableView.getColumns().add(coluna);
				}

				tableView.setItems(dao.listarDados(sqlSelect));
			}
		});

	}

	public void atualizarDados() {
		atualizarDados(sqlSelect);
	}
	
	public void atualizarDados(String sqlSelect) {
		Platform.runLater(new Runnable() {
			@Override
			public void run() {
				tableView.setItems(dao.listarDados(sqlSelect));
			}
		});
	}

	public String getValorSelecionado(int indiceColuna){
 	    ObservableList<StringProperty> linha = tableView.getSelectionModel().getSelectedItem();
 	    if (linha != null){
 	    	StringProperty prop = linha.get(indiceColuna);
 	    	return (prop != null) ? prop.getValue() : null;
 	    }
 	    
 	    return null;
	}
	
	public void limparDados(){
		tableView.setItems(null);
	}

}