/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 Nuts Develop Team.
 *
 * Nuts Framework 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 3 of the License any later version.
 * 
 * Nuts Framework 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 Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.aems.action.tools;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import nuts.aems.WebApplet;
import nuts.core.lang.ExceptionUtils;
import nuts.core.lang.MethodUtils;
import nuts.core.lang.StringUtils;
import nuts.core.sql.SqlUtils;


/**
 */
public class SqlExecuteAction extends AbstractSqlExecuteAction {

	private DataSource dataSource;

	/**
	 */
	public SqlExecuteAction() {
		try {
			dataSource = (DataSource)MethodUtils.invokeMethod(WebApplet.get().getDataAccessClient(), "getDataSource");
		}
		catch (Exception e) {
		}
	}

	/**
	 * @return the dataSource
	 */
	public DataSource getDataSource() {
		return dataSource;
	}

	/**
	 * @param dataSource the dataSource to set
	 */
	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	/**
	 * execute
	 * @return INPUT
	 * @throws Exception if an error occurs
	 */
	public String execute() throws Exception {
		String sql = removeComment(this.sql);
		
		if (StringUtils.isNotEmpty(sql)) {
			Connection con = getDataSource().getConnection();
			results = new ArrayList<Result>();

			String[] ss = sql.split(delimiter);
			for (String s : ss) {
				s = s.trim();
				if ("exit".equalsIgnoreCase(s)) {
				}
				else if ("commit".equalsIgnoreCase(s)) {
					Result r = new Result(s);
					results.add(r);
					try {
						con.commit();
					}
					catch (Exception e) {
						r.setError(ExceptionUtils.getStackTrace(e));
						if (!ignoreError) {
							break;
						}
					}
				}
				else if (s.length() > 0) {
					boolean e = execSql(con, s);
					if (!e && !ignoreError) {
						break;
					}
				}
			}

			SqlUtils.closeQuietly(con);
		}

		return INPUT;
	}

	private boolean execSql(Connection con, String sql) throws Exception {
		Result r = new Result(sql);
		results.add(r);

		sql = StringUtils.replaceChars(sql, "\r\n\t", " ");
		Statement st = null;
		try {
			st = con.createStatement();
			st.execute(sql);
			
			ResultSet rs = st.getResultSet();
			if (rs != null) {
				List<String[]> list = new ArrayList<String[]>();
				r.setResultSet(list);

				String[] row;

				ResultSetMetaData meta = rs.getMetaData();
				int cnt = meta.getColumnCount();

				row = new String[cnt];
				for (int i = 1; i <= cnt; i++) {
					row[i - 1] = meta.getColumnLabel(i);
				}
				list.add(row);
				
				while (rs.next() && (fetchLimit < 1 || list.size() - 1 < fetchLimit)) {
					row = new String[cnt];
					for (int i = 1; i <= cnt; i++) {
						int type = meta.getColumnType(i);
						if (SqlUtils.isBinaryType(type)) {
							byte[] bs = rs.getBytes(i);
							if (bs != null) {
								row[i - 1] = "(" + bs.length + "B)";
							}
						}
						else {
							row[i - 1] = rs.getString(i);
						}
					}
					list.add(row);
				}
			}
			else {
				r.setUpdateCount(st.getUpdateCount());
			}
		}
		catch (Exception e) {
			r.setError(e.getClass().getName() 
				+ ": " + e.getMessage() + "\r\n"
				+ ExceptionUtils.getStackTrace(e));
			return false;
		}
		finally {
			SqlUtils.closeQuietly(st);
		}
		return true;
	}
}
