/**
 * Project: mysql NetLogo extension
 * Author:  Yuelei LI
 * Date:	18 December 2010
 * Tianjin University, China
 * 
 * Copyright (C) 2010 Yuelei LI. All rights reserved.
 * Email: yuelei.li@gmail.com  liyuelei@tju.edu.cn
 * This file is part of mysql NetLogo extension.
 * 
 * myslq NetLogo extension 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, or
 * (at your option) any later version.
 * 
 * mysql NetLogo extension 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 mysql NetLogo extension.  If not, see <http://www.gnu.org/licenses/>.
  * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 */ 


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import org.nlogo.api.Argument;
import org.nlogo.api.Context;
import org.nlogo.api.DefaultReporter;
import org.nlogo.api.ExtensionException;
import org.nlogo.api.LogoList;
import org.nlogo.api.Syntax;

public class ExecuteQuery extends DefaultReporter {
	Connection connection;
	Statement statement;

	public Syntax getSyntax() {
		return Syntax.reporterSyntax(new int[] { Syntax.TYPE_STRING,
				Syntax.TYPE_STRING }, Syntax.TYPE_LIST);
	}

	public Object report(Argument[] argument, Context context)
			throws ExtensionException {
		LogoList rsList = new LogoList();

		try {
			String url = argument[0].getString();
			Class.forName("com.mysql.jdbc.Driver");
			this.connection = DriverManager.getConnection(url);
			this.statement = this.connection.createStatement();

			String query = argument[1].getString();
			this.statement.executeQuery(query);

			ResultSet resultSet = this.statement.getResultSet();
			ResultSetMetaData resultSetMetaData = resultSet
					.getMetaData();
			int numColumn = resultSetMetaData.getColumnCount();
			while (resultSet.next()) {
				LogoList currentList = new LogoList();
				for (int i = 1; i <= numColumn; i++) {
					currentList.add(resultSet.getString(i));
				}
				rsList.add(currentList);
			}

			this.connection.close();
			this.statement.close();
		} catch (Exception e) {
			rsList.add(e.getMessage());
		}

		return rsList;
	}
}