package com.sap.dbmtk.demo;

import java.sql.Types;
import java.util.ArrayList;
import java.util.List;

import com.sap.dbmtk.demo.SqlStatement.Type;
import com.sap.dbmtk.demo.ui.GTable;
import com.sap.dbmtk.demo.utils.StringUtil;


public class DataPanelOrderDetails
extends DataPanelAbstract
{
	private static final long serialVersionUID = 1L;
	public static final String NAME = "Order Detail(s)";

	private String[] _order_ids  = {};

	public DataPanelOrderDetails(DemoApp owner)
	{
		super(owner, NAME, true);
	}

	@Override public boolean showAddButton()    { return false; }
	@Override public boolean showChangeButton() { return false; }
	@Override public boolean showRemoveButton() { return false; }

	@Override
	public void onParentTableSelection(DataPanelAbstract parent)
	{
//System.out.println(getName() + ": onParentTableSelection("+parent.getName()+"): "+StringUtil.toCommaStr(parent.getTable().getSelectedRows()));

		// Orders
		if (DataPanelOrders.NAME.equals(parent.getName()))
		{
			GTable tab = parent.getTable();

			int[] selectedRows = tab.getSelectedRows();

			// Allocate some strings for AU_ID
			_order_ids = new String[selectedRows.length];

			for (int r=0; r<selectedRows.length; r++)
			{
				String str = tab.getValueAsString(selectedRows[r], "order_id", false);
				if (str != null)
					_order_ids[r] = str;
			}
//System.out.println(getName() + ": onParentTableSelection("+parent.getName()+"): OrderId's: "+StringUtil.toCommaStr(_order_ids));
		}

		// Refresh the local table, which will call getTableDataSqlStatement() to get a SqlStatement to execute
		refreshTableData();
	}

	@Override
	public SqlStatement getTableDataSqlStatement()
	{
//		String where = "where 1=2 \n";
//		if (_order_ids.length > 0)
//			where = "where od.order_id in (" + StringUtil.toCommaStr(_order_ids) + ") \n";
//
//		return new SqlStatement(Type.LANGUAGE,
//			"select od.order_id, od.quantity, od.discount, t.title, t.isbn, od.title_id \n"
//			+ "from orderdetails od \n"
//			+ "left outer join titles t on od.title_id = t.title_id \n"
//			+ where
//			+ "order by od.order_id, od.quantity desc \n");

		String order_id_values = null;
		if (_order_ids.length > 0)
			order_id_values = StringUtil.toCommaStr(_order_ids, ",");

		SqlStatement stmnt = new SqlStatement(Type.CALLABLE, "{call get_order_details(?,?)}");
		stmnt.addParam( SqlStatementParam.createInParam("order_id_list", Types.VARCHAR, order_id_values) );
		stmnt.addParam( SqlStatementParam.createOracleResultSetParam("a_cursor") );

		return stmnt;
	}

	@Override
	public List<String> getHiddenColumns()
	{
		List<String> hiddenCols = new ArrayList<String>();
		hiddenCols.add("title_id");
		return hiddenCols;
	}
}
