package eu.dnetlib.enabling.ui.common.widgets;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;




public class GWTTable extends SimplePanel {
	private FlexTable table = new FlexTable();
	
	private boolean headers = false;
	private boolean nline = true;
	private List<String> titles = null; 

	
	public GWTTable() {
		this((List<String>) null, true);
	}

	public GWTTable(String titles, boolean nline) {
		this(Arrays.asList(titles.split("\\|")), nline);
	}

	public GWTTable(List<String> titles, boolean nline) {
		super();
		this.nline = nline;
		this.titles = titles;
		this.headers = ((titles != null)&&(titles.size() > 0));
		resetTable();
	}


	@Override
	public void clear() {
		super.clear();
		resetTable();
	}

	private void resetTable() {
		while (table.getRowCount() > 0) {
			table.removeRow(0);
		}
		table.setStyleName("tableMain");
		setWidget(table);
		
		if (headers) {
			int i = nline ? 1 : 0;
			for (String s : titles) { table.setHTML(0, i++, s);	}
			table.getRowFormatter().setStyleName(0, "cellHead");
		}
	}
	
	
	public void addLongRow(Widget w) {
		int row = table.getRowCount();
		int width = table.getCellCount(0);
		table.getFlexCellFormatter().setColSpan(row, 0, width);
		table.setWidget(row, 0, w);
	}

	
	
	public void addRowHTML(List<String> row) {
		List<Widget> row2 = new ArrayList<Widget>();
		for (String s : row) {
			row2.add(new HTML(s));
		}
		addRowWidgets(row2);
	}

	public void addRowWidgets(List<Widget> row) {
		addRowWidgets(row, true);
	}

	public void addRowWidgets(List<Widget> row, boolean styleOnTop) {
		int rc = table.getRowCount();
		int i=0;
		
		int count = rc;
		if (!headers) count = rc + 1;
		
		if (nline) {
			table.getFlexCellFormatter().setColSpan(rc, i, 1);
			table.setText(rc, i++, "" + count);
		}
		
		for (Widget s : row) {
			table.getFlexCellFormatter().setColSpan(rc, i, 1);
			table.setWidget(rc, i++, s);
		}
		
		if (styleOnTop) table.getRowFormatter().addStyleName(rc, "cellSel");
		
	}
	
}
