/*
 * =============================================================================
 * Projrct F-11 - Web SCADA for Java
 * Copyright (C) 2002 Freedom, Inc. All Rights Reserved.
 *
 * This program 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 2
 * 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 */

package org.F11.scada.tool.timeset;

import java.rmi.RemoteException;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.F11.scada.tool.login.PermissionCheck;
import org.F11.scada.util.RmiUtil;
import org.F11.scada.xwife.explorer.timeset.TimeSetUtil;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.DynaValidatorForm;

public class TimesetAction extends Action {

	public ActionForward execute(ActionMapping mapping,
			ActionForm form,
			HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		if (!PermissionCheck.check("timeset", request))
			return (mapping.getInputForward());
		setRequest(request, form);
		return (mapping.findForward("continue"));
	}

	private void setRequest(HttpServletRequest request, ActionForm form)
			throws RemoteException {
		TimeSetUtil util =
			(TimeSetUtil) RmiUtil.lookupServer(TimeSetUtil.class);
		util.setSystemDate(getDate(form));
	}

	private Date getDate(ActionForm form) {
		DynaValidatorForm actionForm = (DynaValidatorForm) form;
		String year = (String) actionForm.get("year");
		String month = (String) actionForm.get("month");
		String day = (String) actionForm.get("day");
		String hour = (String) actionForm.get("hour");
		String minute = (String) actionForm.get("minute");
		String second = (String) actionForm.get("second");

		System.out.println(year
			+ "/"
			+ month
			+ "/"
			+ day
			+ " "
			+ hour
			+ ":"
			+ minute
			+ ":"
			+ second);
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.MILLISECOND, 0);
		cal.set(
			perseInt(year),
			perseInt(month),
			perseInt(day),
			perseInt(hour),
			perseInt(minute),
			perseInt(second));
		return cal.getTime();
	}

	private int perseInt(String s) {
		return Integer.parseInt(s);
	}
}
