/******************************************************************************
 * Product: Compiere ERP & CRM Smart Business Solution                        *
 * Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved.                *
 * This program is free software, you can redistribute it and/or modify it    *
 * under the terms version 2 of the GNU General Public License as published   *
 * by the Free Software Foundation. This program is distributed in the hope   *
 * that it will be useful, but WITHOUT ANY WARRANTY, without even the implied *
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.           *
 * See the GNU General Public License for more details.                       *
 * You should have received a copy of the GNU General Public License along    *
 * with this program, if not, write to the Free Software Foundation, Inc.,    *
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.                     *
 * For the text or an alternative of this public license, you may reach us    *
 * ComPiere, Inc., 3600 Bridge Parkway #102, Redwood City, CA 94065, USA      *
 * or via info@compiere.org or http://www.compiere.org/license.html           *
 *****************************************************************************/
package org.compiere.model;

import java.sql.*;
import java.util.*;
import java.util.logging.*;
import org.compiere.util.*;

/**
 *	Tab Model
 *	
 *  @author Jorg Janke
 *  @version $Id: MTab.java,v 1.1 2008/01/16 07:34:29 jrmt Exp $
 */
public class MTab extends X_AD_Tab
{
	
	/**
     * 	Get MTab from Cache
     *	@param ctx context
     *	@param AD_Tab_ID id
     *	@return MTab
     */
    public static MTab get(Ctx ctx, int AD_Tab_ID)
    {
	    Integer key = new Integer(AD_Tab_ID);
	    MTab retValue = (MTab)s_cache.get(key);
	    if (retValue != null)
		    return retValue;
	    retValue = new MTab(ctx, AD_Tab_ID, null);
	    if (retValue.get_ID() != 0)
		    s_cache.put(key, retValue);
	    return retValue;
    } //	get

    /**	Cache						*/
    private static CCache<Integer, MTab> s_cache 
    	= new CCache<Integer, MTab>("AD_Tab", 20);

	/**************************************************************************
	 * 	Standard Constructor
	 *	@param ctx context
	 *	@param AD_Tab_ID id
	 *	@param trxName transaction
	 */
	public MTab (Ctx ctx, int AD_Tab_ID, String trxName)
	{
		super (ctx, AD_Tab_ID, trxName);
		if (AD_Tab_ID == 0)
		{
		//	setAD_Window_ID (0);
		//	setAD_Table_ID (0);
		//	setName (null);
			setEntityType (ENTITYTYPE_UserMaintained);	// U
			setHasTree (false);
			setIsReadOnly (false);
			setIsSingleRow (false);
			setIsSortTab (false);	// N
			setIsTranslationTab (false);
			setSeqNo (0);
			setTabLevel (0);
			setIsInsertRecord(true);
			setIsAdvancedTab(false);
		}
	}	//	M_Tab

	/**
	 * 	Load Constructor
	 *	@param ctx context
	 *	@param rs result set
	 *	@param trxName transaction
	 */
	public MTab (Ctx ctx, ResultSet rs, String trxName)
	{
		super(ctx, rs, trxName);
	}	//	M_Tab

	/**
	 * 	Parent Constructor
	 *	@param parent parent
	 */
	public MTab (MWindow parent)
	{
		this (parent.getCtx(), 0, parent.get_TrxName());
		setClientOrg(parent);
		setAD_Window_ID(parent.getAD_Window_ID());
		setEntityType(parent.getEntityType());
	}	//	M_Tab

	/**
	 * 	Parent Constructor
	 *	@param parent parent
	 *	@param from copy from
	 */
	public MTab (MWindow parent, MTab from)
	{
		this (parent.getCtx(), 0, parent.get_TrxName());
		copyValues(from, this);
		setClientOrg(parent);
		setAD_Window_ID(parent.getAD_Window_ID());
		setEntityType(parent.getEntityType());
	}	//	M_Tab
	
	
	/**	The Fields						*/
	private MField[]				m_fields = null;
	/** Map of ColumnName and AD_Field_ID	*/
	private HashMap<String,Integer>	m_columnNameField = null;

	/**
	 * 	Get Fields
	 *	@param reload reload data
	 *	@return array of lines
	 *	@param trxName transaction
	 */
	public MField[] getFields (boolean reload, String trxName)
	{
		if (m_fields != null && !reload)
			return m_fields;
		String sql = "SELECT * FROM AD_Field WHERE AD_Tab_ID=? ORDER BY SeqNo";
		ArrayList<MField> list = new ArrayList<MField>();
		PreparedStatement pstmt = null;
		try
		{
			pstmt = DB.prepareStatement (sql, trxName);
			pstmt.setInt (1, getAD_Tab_ID());
			ResultSet rs = pstmt.executeQuery ();
			while (rs.next ())
				list.add (new MField (getCtx(), rs, trxName));
			rs.close ();
			pstmt.close ();
			pstmt = null;
		}
		catch (Exception e)
		{
			log.log(Level.SEVERE, sql, e);
		}
		try
		{
			if (pstmt != null)
				pstmt.close ();
			pstmt = null;
		}
		catch (Exception e)
		{
			pstmt = null;
		}
		//
		m_fields = new MField[list.size ()];
		list.toArray (m_fields);
		return m_fields;
	}	//	getFields

	/**
	 * 	Get Field with ID
	 *	@param AD_Field_ID id
	 *	@return field or null
	 */
	public MField getField (int AD_Field_ID)
	{
		if (AD_Field_ID == 0)
			return null;
		MField[] fields = getFields(false, get_TrxName());
		for (int i = 0; i < fields.length; i++)
        {
			if (fields[i].getAD_Field_ID() == AD_Field_ID)
				return fields[i];
        }
		return null;
	}	//	getField
	
	/**
	 * 	Get Field with name
	 *	@param columnName name
	 *	@return field or null
	 */
	public MField getField (String columnName)
	{
		int AD_Field_ID = getAD_Field_ID(columnName);
		return getField(AD_Field_ID);
	}	//	getField
	
	/**
	 * 	Get AD_Field_ID in tab
	 *	@param columnName name
	 *	@return id
	 */
	public int getAD_Field_ID (String columnName)
	{
		if (m_columnNameField == null)
			fillColumnNameField();
		Integer AD_Field_ID = m_columnNameField.get(columnName);
		if (AD_Field_ID == null)
			return 0;
		return AD_Field_ID.intValue();
	}	//	getAD_Field_ID
	
	/**
	 * 	Fill ColumnName Field map
	 */
	private void fillColumnNameField()
	{
		m_columnNameField = new HashMap<String,Integer>();
		String sql = "SELECT ColumnName, f.AD_Field_ID "
			+ "FROM AD_Field f"
			+ " INNER JOIN AD_Column c ON (f.AD_Column_ID=c.AD_Column_ID) "
			+ "WHERE f.AD_Tab_ID=?";
		PreparedStatement pstmt = null;
        try
        {
	        pstmt = DB.prepareStatement(sql, null);
	        pstmt.setInt(1, getAD_Tab_ID());
	        ResultSet rs = pstmt.executeQuery();
	        while (rs.next())
	        {
	        	String columnName = rs.getString(1);
	        	int AD_Field_ID = rs.getInt(2);
	        	m_columnNameField.put(columnName, AD_Field_ID);
	        }
	        rs.close();
	        pstmt.close();
	        pstmt = null;
        }
        catch (Exception e)
        {
	        log.log(Level.SEVERE, sql, e);
        }
        try
        {
	        if (pstmt != null)
		        pstmt.close();
	        pstmt = null;
        }
        catch (Exception e)
        {
	        pstmt = null;
        }
	}	//	fillColumnNameField

	
	/**
	 * 	Before Save
	 *	@param newRecord new
	 *	@return true
	 */
	protected boolean beforeSave (boolean newRecord)
	{
	//	UPDATE AD_Tab SET IsInsertRecord='N' WHERE IsInsertRecord='Y' AND IsReadOnly='Y'
		if (isReadOnly() && isInsertRecord())
			setIsInsertRecord(false);
		return true;
	}
	
	/**
	 * 	String Info
	 * 	@return info
	 */
	public String toString()
	{
		StringBuffer sb = new StringBuffer("MTab[");
		sb.append(get_ID())
			.append("-").append(getName())
			.append("]");
		return sb.toString();
	}	//	toString

}	//	M_Tab
