/*
 * Copyright (C) 2005 - 2011 Jaspersoft Corporation. All rights reserved.
 * http://www.jaspersoft.com.
 *
 * Unless you have purchased  a commercial license agreement from Jaspersoft,
 * the following license terms  apply:
 *
 * This program is free software: you can redistribute it and/or  modify
 * it under the terms of the GNU Affero General Public License  as
 * published by the Free Software Foundation, either version 3 of  the
 * License, or (at your option) any later version.
 *
 * This program 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 Affero  General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public  License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package com.jaspersoft.jasperserver.api.engine.jasperreports.util;

import java.sql.ResultSet;
import java.util.Date;
import java.util.TimeZone;

import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JRField;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRDataSource;
import org.quartz.TriggerUtils;

/**
 * @author Ionut Nedelcu (ionutned@users.sourceforge.net)
 * @version $Id
 */
public class JRTimezoneResultSetDataSource implements JRDataSource
{
	private TimeZone timezone;
	private JRDataSource dataSource;


	public JRTimezoneResultSetDataSource(JRDataSource dataSource, TimeZone timezone)
	{
		this.dataSource = dataSource;
		this.timezone = timezone;
	}

	public boolean next() throws JRException
	{
		boolean hasNext = false;
		if (dataSource != null) {
			try {
				hasNext = dataSource.next();
			} catch (JRException e) {
				throw new JRException("Unable to get next record.", e);
			}
		}

		return hasNext;
	}

	public Object getFieldValue(JRField field) throws JRException
	{
		Object value = null;
		if (field != null && dataSource != null) {
			value = dataSource.getFieldValue(field);

			if (value instanceof Date && timezone != null) {
				Date initialDate = (Date) value;
				Date date = TriggerUtils.translateTime(initialDate, TimeZone.getTimeZone("GMT"), timezone);
				initialDate.setTime(date.getTime());
				return initialDate;
			}

			return value;
		}

		return value;
	}
}
