/*
 * MiningMart Version 1.0
 * 
 * Copyright (C) 2006 Martin Scholz, Timm Euler, 
 *                    Daniel Hakenjos, Katharina Morik
 *
 * Contact: miningmart@ls8.cs.uni-dortmund.de
 *
 * A list of contributing developers (other than the copyright 
 * holders) can be found at
 * http://mmart.cs.uni-dortmund.de/downloads/download.html
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * 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, see the file MM_HOME/LICENSE; if not, write
 * to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
 * Floor, Boston, MA 02110-1301, USA.
 */
package edu.udo.cs.miningmart.m4.core;

import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;

import edu.udo.cs.miningmart.db.DB;
import edu.udo.cs.miningmart.exception.DbConnectionClosed;
import edu.udo.cs.miningmart.exception.M4Exception;

/**
 * @author Martin Scholz
 * @version $Id: OperatorGroup.java,v 1.3 2006/04/11 14:10:14 euler Exp $
 */
public class OperatorGroup implements edu.udo.cs.miningmart.m4.OperatorGroup,Serializable {

	/** Name of the operator group m4 table */
	public static final String M4_TABLE_NAME = "op_group_t";
	
	/** Name of the operator group primary key attribute */
	public static final String ATTRIB_OPGROUP_ID     = "opg_id";     // NUMBER NOT NULL,

	/** Name of the operator group's parent group */
	public static final String ATTRIB_OPGROUP_PARENT = "opg_parent"; // NUMBER

	/** Name of the operator group's operator foreign key attribute */
	public static final String ATTRIB_OPG_OPID       = "opg_opid";   // NUMBER NOT 

	/** Name of the operator group's name attribute */
	public static final String ATTRIB_OPGROUP_NAME   = "opg_name";   // VARCHAR2(100) NOT NULL

	// *****
	
	class OpGroupEntry {
		private final long myId;
		private final Long myParent;
		private final String myName;
		private final long myOperator;
		
		OpGroupEntry(long id, String name, Long parent, long operator) {
			this.myId = id;	
			this.myParent = parent;
			this.myName = name;
			this.myOperator = operator;
		}
		
		long getId() { return this.myId; }
		
		String getName() { return this.myName; }
		
		Operator getOperator() throws M4Exception {
			if (this.myOperator == 0)
				return null;
			else {
				return (Operator) m4db.getM4Object(this.myOperator, Operator.class);
			}	
		}
		
		OpGroupEntry getParent() {
			if (this.myParent == null)
				return null;
			else return (OpGroupEntry) opGroupEntries.get(this.myParent);
		}
	}


	// ***** Private fields *****
	
	/** Data structure for mapping the IDs to names: */
	private HashMap opGroupEntries = new HashMap();
	
	/** The HCI needs to create the tree top-down! */
	private HashMap parentToChildLookUp = new HashMap();

	private DB m4db;

	private static final Long TOP_LEVEL_ID = new Long(0);
		
	public OperatorGroup(DB db) throws M4Exception, DbConnectionClosed
	{
		this.m4db = db;
		
		String query = "SELECT " + ATTRIB_OPGROUP_ID
					      + ", " + ATTRIB_OPGROUP_PARENT
					      + ", " + ATTRIB_OPG_OPID
					      + ", " + ATTRIB_OPGROUP_NAME
					      + " FROM "  + M4_TABLE_NAME;
					 
		ResultSet rs = null;
		try {	 	
			rs = db.executeM4SqlRead(query);
			L: while (rs.next()) {
				long id = rs.getLong(ATTRIB_OPGROUP_ID);
				if (rs.wasNull()) {
					continue L;
				}
				long operator = rs.getLong(ATTRIB_OPG_OPID);
				String name = rs.getString(ATTRIB_OPGROUP_NAME);
				Long parent = new Long(rs.getLong(ATTRIB_OPGROUP_PARENT));
				if (rs.wasNull()) {
					parent = null;				
				}
				
				// create an object for this entry:
				OpGroupEntry oge = new OpGroupEntry(id, name, parent, operator);
				Long idL = new Long(id);
				
				// add the entry to the collection:
				this.opGroupEntries.put(idL, oge);
				
				// if there is no parent then remember the ID as a top-level entry,
				// otherwise store it in the parent to child lookup map:
				Long lookUpId = (parent == null ? TOP_LEVEL_ID : parent);
				Collection childSet = (Collection) this.parentToChildLookUp.get(lookUpId);
				if (childSet == null) {
					childSet = new HashSet();
					this.parentToChildLookUp.put(lookUpId, childSet);
				}
				childSet.add(idL);
			}
		}
		catch (SQLException e) {
			throw new M4Exception(
				"SQLException when trying to read the OperatorGroup table:\n" +
				e.getMessage());
		}
		finally {
			DB.closeResultSet(rs);
		}
	}

	/**
	 * @return a <code>Collection</code> of IDs of type <code>Long</code>
	 * representing operator groups. This IDs can be used to query further
	 * information about the group using the methods of this class.
	 */	
	public Collection getTopLevelOperatorGroups() {
		return (Collection) this.parentToChildLookUp.get(TOP_LEVEL_ID);
	}

	/** 
	 * @param id the ID of an operator group
	 * @return the name of the operator group with the specified ID
	 */
	public String getGroupName(Long id) {
		OpGroupEntry oge = (OpGroupEntry) this.opGroupEntries.get(id);
		if (oge != null)
			return oge.getName();
		else return null;
	}

	/** 
	 * @param id the ID of an operator group
	 * @return an <code>Operator</code> if the ID refers to a single operator
	 * entry, rather than to a group.
	 */
	public edu.udo.cs.miningmart.m4.Operator getOperator(Long id) throws M4Exception {
		OpGroupEntry oge = (OpGroupEntry) this.opGroupEntries.get(id);
		if (oge != null)
			return oge.getOperator();
		else return null;
	}

	/** 
	 * @param id the ID of an operator group
	 * @return the ID of the parent operator group or <code>null</code>, if the ID
	 * belongs to a top-level operator group.
	 */
	public Long getParentGroup(Long id) {
		OpGroupEntry oge = (OpGroupEntry) this.opGroupEntries.get(id);
		if (oge != null) {
			oge = oge.getParent();
			if (oge != null) {
				return new Long(oge.getId());
			}
		}
		return null;
	}

	/** 
	 * @param id the ID of an operator group
	 * @return a <code>Collection</code> of the ID of all child operator groups
	 * (or operator instances) referred to with their <code>Long</code> IDs.
	 * If the specified id is unknown or does not contain sub-elements, then
	 * <code>null</code> is returned.
	 */
	public Collection getChildGroups(Long id) {
		Collection col = (Collection) this.parentToChildLookUp.get(id);
		if (col != null && col.isEmpty()) {
			return null;	
		}
		else return col;
	}

}
/*
 * Historie
 * --------
 * 
 * $Log: OperatorGroup.java,v $
 * Revision 1.3  2006/04/11 14:10:14  euler
 * Updated license text.
 *
 * Revision 1.2  2006/04/06 16:31:14  euler
 * Prepended license remark.
 *
 * Revision 1.1  2006/01/03 09:54:18  hakenjos
 * Initial version!
 *
 */
