/**
 * Copyright (c) 2004, yher2 project
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * * Redistributions of source code must retain the above copyright notice, 
 *   this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright notice, 
 *   this list of conditions and the following disclaimer in the documentation 
 *   and/or other materials provided with the distribution.
 * * Neither the name of the nor the names of its contributors may be used to endorse or 
 *   promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
 * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 
 * SUCH DAMAGE.
 */
package net.yher2.junit.db.data;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import net.yher2.commons.collections.CollectionUtils;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @auther  hisaboh
 */
public class Table {
	Log log = LogFactory.getLog(this.getClass());
	String name;
	Header header[];
	List rowList;
	
	public Table(String name) {
		this.name = name;
		header = new Header[0];
		rowList = new ArrayList();
	}
	
	/**
	 * @return Returns the header.
	 */
	public Header[] getHeader() {
		return header;
	}
	/**
	 * @param header The header to set.
	 */
	public void setHeader(Header[] header) {
		this.header = header;
	}
	public void addRow(Row row) {
		rowList.add(row);
	}
	public Row[] getRow() {
		return (Row[])rowList.toArray(new Row[rowList.size()]);
	}
	/**
	 * @return Returns the name.
	 */
	public String getName() {
		return name;
	}
	
	public void insert(Connection con) throws SQLException {
		PreparedStatement ps = null;
		String sql = 
			"INSERT INTO " + getName() + "("+getHeaderCsv()+")" +
			" VALUES(" + getArgumentCsv()+")";
		try {
			ps = con.prepareStatement(sql);
			log.debug(sql);
		
			Row row[] = getRow();
			for (int i=0; i<row.length; i++) {
				row[i].set(ps);
				ps.executeUpdate();
			}
		} finally {
			if (ps != null) ps.close();
		}
	}
	
	private String getHeaderCsv() {
		if (header.length == 0) return "";
		String csv = "";
		for (int i=0; i<header.length; i++) {
			csv += header[i].getName() + ",";
		}
		return csv.substring(0, csv.length()-1);
	}
	private String getArgumentCsv() {
		if (header.length == 0) return "";
		String csv = "";
		for (int i=0; i<header.length; i++) {
			csv += "?,";
		}
		return csv.substring(0, csv.length()-1);
	}

	/**
	 * @param con
	 * @throws SQLException
	 */
	public void delete(Connection con) throws SQLException {
		String sql = "delete from " + getName() + " where ";
		String condition = "";
		Header pk[] = getPrimaryKey();
		if (pk.length == 0) {
			throw new IllegalStateException(getName() + ": There is no primary key header.");
		}
		for (int i=0; i<pk.length; i++) {
			condition += pk[i].getName() + "=? and ";
		}
		
		sql += condition.substring(0, condition.length()-4);
		
		PreparedStatement ps = null;
		try {
			log.debug(sql);
			ps = con.prepareStatement(sql);
			int pkIndex[] = getPrimaryKeyIndex();
			Row row[] = getRow();
			for (int i=row.length-1; i>=0; i--) {
				ColumnData column[] = row[i].getColumn();
				ArrayList list = new ArrayList();
				for (int j=0; j<pkIndex.length; j++) {
					column[pkIndex[j]].set(j+1, ps);
					list.add(header[pkIndex[j]].getName()+"="+column[pkIndex[j]].getValue());
				}
				log.debug("SET: " + CollectionUtils.toCsv(list));
				ps.executeUpdate();
			}
		} finally {
			if (ps != null) ps.close();
		}
	}
	
	private Header[] getPrimaryKey() {
		ArrayList pkList = new ArrayList();
		for (int i=0; i<header.length; i++) {
			if (header[i].isPrimaryKey()) pkList.add(header[i]);
		}
		return (Header[])pkList.toArray(new Header[pkList.size()]);
	}
	private int[] getPrimaryKeyIndex() {
		ArrayList list = new ArrayList();
		for (int i=0; i<header.length; i++) {
			if (header[i].isPrimaryKey()) list.add(new Integer(i));
		}
		return ArrayUtils.toPrimitive((Integer[])list.toArray(new Integer[list.size()]));
	}
}
