package profileEngine;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ListIterator;

import dataWarehousingTools.LogFile;

public class NullCount
{
	
	public NullCount
	(
		String databaseProduct, 
		Connection connection, 
		String databaseName, 
		String schemaName,
		String tableName, 
		String partsInName,
		ColumnList columnList, 
		Metadata metadata,
		LogFile logFile
	)
	{
		ListIterator<ColumnElement> iterator;
		ColumnElement columnElement;
		Statement statement = null;
		ResultSet resultSet = null;
		String query;
		String tableSpecification;

		if (partsInName.equals("3"))
			tableSpecification = new String(databaseName + "." + schemaName + "." + tableName);
		else if (partsInName.equals("2"))
			tableSpecification = new String(schemaName + "." + tableName);
		else
			tableSpecification = new String(tableName);

		for (iterator = columnList.listIterator(); iterator.hasNext();)
		{
			columnElement = (ColumnElement) iterator.next(); 
			//
			// If nulls are not allowed, then there cannot be any,
			// so there is no point in running the query to count them. 
			//
			if (columnElement.getNullable().equals("Y"))
			{			
				try
				{
					statement = connection.createStatement();
				} 
				catch (SQLException e)
				{
					e.printStackTrace();
				}
				
				query = new String
				(
					"select " +
					    "count(*) as null_count " +
					"from " +
					    tableSpecification + " " +
					"where " +
					    columnElement.getColumnName() + " is null"
				);
					
				logFile.logMessage(query);
				
				try
				{
					resultSet = statement.executeQuery(query);
				} 
				catch (SQLException e)
				{
					e.printStackTrace();
				}
				
				try
				{
					if (resultSet.next())
					{
						columnElement.setNullCount(resultSet.getLong("null_count"));
						metadata.updateColumnProfile
						(
							columnElement.getColumnProfileId(),
							columnElement.getNullCount()
						);
					}
				} 
				catch (SQLException e)
				{
					e.printStackTrace();
				}
			}
		}
	}
}
