/*
 * 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.util.Collection;
import java.util.Iterator;

import edu.udo.cs.miningmart.db.DB;
import edu.udo.cs.miningmart.exception.M4CompilerError;
import edu.udo.cs.miningmart.exception.M4Exception;
import edu.udo.cs.miningmart.exception.UserError;
import edu.udo.cs.miningmart.m4.ParameterObject;
import edu.udo.cs.miningmart.m4.utils.M4Info;
import edu.udo.cs.miningmart.m4.utils.M4InfoEntry;
import edu.udo.cs.miningmart.m4.utils.Print;
import edu.udo.cs.miningmart.m4.utils.XmlInfo;
import edu.udo.cs.miningmart.operator.ExecutableOperator;

/**
 * Objects of this class represent M4 assertions.
 * These assertions are tuples stored in the table <code>OP_ASSERT_T</code>.
 * 
 * @author Martin Scholz
 * @version $Id: Assertion.java,v 1.5 2006/04/11 14:10:14 euler Exp $
 */
public class Assertion extends M4Data implements XmlInfo, edu.udo.cs.miningmart.m4.Assertion {

	/** The name of the corresponding M4 table. */
	public static final String M4_TABLE_NAME = "op_assert_t";

	/** db level: name of the assertion's id attribute */
	public static final String ATTRIB_ASSERT_ID = "assert_id";

	/** db level: name of the operator id attribute */
	public static final String ATTRIB_OPERATOR_ID = "assert_opid";

	/** db level: name of the attribute specifying the assertion type */
	public static final String ATTRIB_ASSERT_TYPE = "assert_type";

	/** db level: name of the attribute for first argument */
	public static final String ATTRIB_ASSERT_OBJ1 = "assert_obj1";

	/** db level: name of the attribute for second argument */
	public static final String ATTRIB_ASSERT_OBJ2 = "assert_obj2";

	
	/** Cache for getM4Info() */
	private static M4Info m4Info = null;

	/** @see M4Table.getM4TableName() */
	public String getM4TableName() {
		return M4_TABLE_NAME;	
	}

	/** @see M4Table.getIdAttributeName() */
	public String getIdAttributeName() {
		return ATTRIB_ASSERT_ID;
	}

	/** @see M4Table.getM4Info() */
	public M4Info getM4Info() {
		if (m4Info == null) {
			M4InfoEntry[] m4i = {
				new M4InfoEntry(ATTRIB_ASSERT_ID,   "getId",            "setId",                long.class,     NOT_NULL),
				new M4InfoEntry(ATTRIB_OPERATOR_ID, "getTheOperator",   "primitiveSetOperator", edu.udo.cs.miningmart.m4.Operator.class, NOT_NULL),
				new M4InfoEntry(ATTRIB_ASSERT_TYPE, "getAssertionType", "setAssertionType",     String.class,   NOT_NULL),
				new M4InfoEntry(ATTRIB_ASSERT_OBJ1, "getObj1",          "setObj1",              String.class,   NOT_NULL),
				new M4InfoEntry(ATTRIB_ASSERT_OBJ2, "getObj2",          "setObj2",              String.class)
			};
			m4Info = new M4Info(m4i);
		}
		return m4Info;
	}
	
	/** Cache for getXmlInfo() */
	private static M4Info xmlInfo = null;

	/** @see M4Table.getM4Info() */
	public M4Info getXmlInfo() {
		if (xmlInfo == null) {
			M4InfoEntry[] m4i = {
				new M4InfoEntry("Operator", "getTheOperator",   "setTheOperator",   edu.udo.cs.miningmart.m4.Operator.class),
				new M4InfoEntry("Type",     "getAssertionType", "setAssertionType", String.class),
				new M4InfoEntry("Obj1",     "getObj1",          "setObj1",          String.class),
				new M4InfoEntry("Obj2",     "getObj2",          "setObj2",          String.class),
				new M4InfoEntry("Docu",     "getDocumentation", "setDocumentation", String.class)
			};
			xmlInfo = new M4Info(m4i);
		}
		return xmlInfo;
	}

	// The private fields of assertion objects:
	private Operator myOperator;
	private String myType;
	private String myObj1;
	private String myObj2;

	/**
	 * @see edu.udo.cs.miningmart.m4.core.M4Data#Constructor
	 */
	public Assertion(DB db) {
		super(db);	
	}

	/**
	 * @see M4Object#print()
	 */
	public void print() {
		edu.udo.cs.miningmart.m4.Operator op = this.getTheOperator();
		String opName = (op == null) ? null : op.getName();

		this.doPrint(Print.M4_OBJECT, "Assertion (Id = " + this.getId() + ";"
				+ " Name = " + this.getName() + "; TYPE = " + this.getAssertionType()
				+ " OBJ1 = " + this.getObj1() + "; OBJ2 = " + this.getObj2()
				+ " Operator = " + opName + ")");

	}
	
	/**
	 * @see edu.udo.cs.miningmart.m4.core.M4Data#getObjectsInNamespace(Class)
	 */
	protected Collection getObjectsInNamespace(Class typeOfObjects) throws M4Exception {
		return null;
	}
	
	/**
	 * Gets the myObj1.
	 * @return Returns a String
	 */
	public String getObj1() {
		return myObj1;
	}

	/**
	 * Gets the myObj2.
	 * @return Returns a String
	 */
	public String getObj2() {
		return myObj2;
	}

	/**
	 * Gets the Operator
	 * @return Returns an <code>Operator</code>
	 */
	public edu.udo.cs.miningmart.m4.Operator getTheOperator() {
		return myOperator;
	}

	/**
	 * Gets the myType.
	 * @return Returns a String
	 */
	public String getAssertionType() {
		return myType;
	}

	/**
	 * Sets the myObj1.
	 * @param myObj1 The myObj1 to set
	 */
	public void setObj1(String myObj1) {
		this.setDirty();
		this.myObj1 = myObj1;
	}

	/**
	 * Sets the myObj2.
	 * @param myObj2 The myObj2 to set
	 */
	public void setObj2(String myObj2) {
		this.setDirty();
		this.myObj2 = myObj2;
	}

	/**
	 * Sets the Operator.
	 * @param operator The <code>Operator</code> to set
	 */
	public void setTheOperator(edu.udo.cs.miningmart.m4.Operator operator) throws M4Exception {
		Operator.op2assert.updateReferenceTo(this, operator);
	}

	/** Primitive setter method. Do not use it! */
	public void primitiveSetOperator(edu.udo.cs.miningmart.m4.Operator operator) {
		this.setDirty();
		this.myOperator = (Operator) operator;	
	}

	/**
	 * Sets the myType.
	 * @param myType The myType to set
	 */
	public void setAssertionType(String myType) {
		this.setDirty();
		this.myType = myType;
	}

	/** @see M4Data#removeAllM4References */
	protected void removeAllM4References() throws M4Exception {
		this.setTheOperator(null);
		this.removeDocObject();
	}
	
	
	public void writeAssertion(ExecutableOperator op)
	throws M4CompilerError {
		String assertionType = this.getAssertionType();
		for (int loop=0; loop < op.getNumberOfLoops(); loop++) {
			if (assertionType.equals(ASSERTION_NOT_NULL))
				assertNotNull(op, loop);
			else if (assertionType.equals(ASSERTION_UNIQUE))
				assertUniqueness(op, loop);
		}
	}
	
	private void assertNotNull(ExecutableOperator exOp, int loop) throws M4CompilerError {
		try {
			String obj1 = this.getObj1();
			ParameterObject[] parArray = exOp.getParameter(obj1, loop);
			Collection columns = Condition.getColumnsForParameter(parArray);
			
			Iterator it = columns.iterator();
			while (it.hasNext()) {
				edu.udo.cs.miningmart.m4.core.Column column = (edu.udo.cs.miningmart.m4.core.Column) it.next();
				column.setNumberOfMissingValues(0);
			}
		}
		catch (M4Exception m4e) {
			throw new M4CompilerError("M4 exception caught when checking assertion '" + this.getAssertionType() + "': " + m4e.getMessage());
		}
	}
	
	// Unique attributes are keys with a "NOT_NULL" constraint. 
	private void assertUniqueness(ExecutableOperator exOp, int loop) throws M4CompilerError {
		try {
			String obj1 = this.getObj1();
			ParameterObject[] parArray = exOp.getParameter(obj1, loop);
			Collection columns = Condition.getColumnsForParameter(parArray);
			
			Iterator it = columns.iterator();
			while (it.hasNext()) {
				edu.udo.cs.miningmart.m4.core.Column column = (edu.udo.cs.miningmart.m4.core.Column) it.next();
				String countS = column.getColumnset().readOrComputeCount();
				try {
					int count = Integer.parseInt(countS);
					column.setNumberOfUniqueValues(count);
					column.setNumberOfMissingValues(0);
				}
				catch (NumberFormatException e) {
					this.doPrint(Print.WARNING, "Could not compute count for Columnset with ID "
							+ column.getColumnset().getId());
				}
			}	
		}
		catch (M4Exception m4e) {
			throw new M4CompilerError("M4 exception caught when checking assertion '" + this.getAssertionType() + "': " + m4e.getMessage());
		}
	}

	// --------------------------------------------------------------
	private static final String ASSERTION_NOT_NULL    = "NOT_NULL";
	private static final String ASSERTION_UNIQUE      = "UNIQUE";

}

/*
 * Historie
 * --------
 * 
 * $Log: Assertion.java,v $
 * Revision 1.5  2006/04/11 14:10:14  euler
 * Updated license text.
 *
 * Revision 1.4  2006/04/06 16:31:13  euler
 * Prepended license remark.
 *
 * Revision 1.3  2006/03/23 11:13:45  euler
 * Improved exception handling.
 *
 * Revision 1.2  2006/03/20 14:02:24  scholz
 * added assertion handling
 *
 * Revision 1.1  2006/01/03 09:54:17  hakenjos
 * Initial version!
 *
 */
