/*
 * 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 nuts.aems.WebApplet;
import nuts.core.dao.sql.SqlUtils;
import nuts.core.lang.Exceptions;
import nuts.core.lang.Methods;
import nuts.core.lang.Strings;

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;


/**
 */
public class SqlExecuteAction extends AbstractSqlExecuteAction {

	private DataSource dataSource;

	/**
	 */
	public SqlExecuteAction() {
		try {
			dataSource = (DataSource)Methods.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 (Strings.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(Exceptions.getStackTrace(e));
						if (!ignoreError) {
							break;
						}
					}
				}
				else if (s.length() > 0) {
					boolean e = execSql(con, s);
					if (!e && !ignoreError) {
						break;
					}
				}
			}

			SqlUtils.safeClose(con);
		}

		return INPUT;
	}

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

		sql = Strings.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"
				+ Exceptions.getStackTrace(e));
			return false;
		}
		finally {
			SqlUtils.safeClose(st);
		}
		return true;
	}
}
