/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2000-2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Apache" and "Apache Software Foundation" and
 *     "Apache Jetspeed" must not be used to endorse or promote products
 *    derived from this software without prior written permission. For
 *    written permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache" or
 *    "Apache Jetspeed", nor may "Apache" appear in their name, without
 *    prior written permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
package org.apache.jetspeed.modules.actions.portlets;

import org.apache.jetspeed.modules.actions.portlets.security.SecurityConstants;
import org.apache.jetspeed.om.registry.CapabilityMap;
import org.apache.jetspeed.om.registry.ClientEntry;
import org.apache.jetspeed.om.registry.base.BaseClientEntry;
import org.apache.jetspeed.portal.portlets.VelocityPortlet;
import org.apache.jetspeed.services.Registry;
import org.apache.jetspeed.util.template.JetspeedLink;
import org.apache.jetspeed.util.template.JetspeedLinkFactory;
import org.apache.turbine.util.DynamicURI;
import org.apache.turbine.util.Log;
import org.apache.turbine.util.RunData;
import org.apache.turbine.util.security.EntityExistsException;
import org.apache.velocity.context.Context;

/**
 * @author Administrator
 *
 * To change the template for this generated type comment go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
public class ClientUpdateAction extends VelocityPortletAction
{

	private static final String CLIENT_UPDATE_PANE = "ClientForm";

	/**
	 * Subclasses must override this method to provide default behavior
	 * for the portlet action
	 */
	/**
	 * Build the normal state content for this portlet.
	 *
	 * @param portlet The velocity-based portlet that is being built.
	 * @param context The velocity context for this request.
	 * @param rundata The turbine rundata context for this request.
	 */
	protected void buildNormalContext(
		VelocityPortlet portlet,
		Context context,
		RunData rundata)
		throws Exception
	{
		String mode =
			rundata.getParameters().getString(SecurityConstants.PARAM_MODE);
		context.put(SecurityConstants.PARAM_MODE, mode);

		String msgid =
			rundata.getParameters().getString(SecurityConstants.PARAM_MSGID);
		if (msgid != null)
		{
			int id = Integer.parseInt(msgid);
			if (id < SecurityConstants.MESSAGES.length)
			{
				context.put(
					SecurityConstants.PARAM_MSG,
					SecurityConstants.MESSAGES[id]);
			}
		}

		if (mode != null
			&& (mode.equals(SecurityConstants.PARAM_MODE_DELETE)
				|| mode.equals(SecurityConstants.PARAM_MODE_UPDATE)))
		{
			String clientName =
				rundata.getParameters().getString("client_name");
			ClientEntry clientEntry =
				(ClientEntry) Registry.getEntry(Registry.CLIENT, clientName);
			context.put("entry", clientEntry);
		}
	}

	/**
	 * Insert a client entry into the registry
	 * @param rundata The turbine rundata context for this request.
	 * @param context The velocity context for this request.
	 * @throws Exception
	 */
	public void doInsert(RunData rundata, Context context) throws Exception
	{
		try
		{
			String clientName =
				rundata.getParameters().getString("client_name");

			if (clientName == null || clientName.length() == 0)
			{
				JetspeedLink link = JetspeedLinkFactory.getInstance(rundata);
				DynamicURI duri =
					link
						.getPaneByName(CLIENT_UPDATE_PANE)
						.addPathInfo(
							SecurityConstants.PARAM_MODE,
							SecurityConstants.PARAM_MODE_INSERT)
						.addPathInfo(
							SecurityConstants.PARAM_MSGID,
							SecurityConstants.MID_INVALID_ENTITY_NAME);
				JetspeedLinkFactory.putInstance(link);
				rundata.setRedirectURI(duri.toString());

				resetForm(rundata);
			}
			else
			{
				//check if profile to be created already exists
				ClientEntry existingClientEntry =
					(ClientEntry) Registry.getEntry(
						Registry.CLIENT,
						clientName);
				if (existingClientEntry != null)
				{
					throw new EntityExistsException(
						"ClientEntry: " + clientName + " Already Exists!");
				}

				BaseClientEntry clientEntry = new BaseClientEntry();
				clientEntry.setName(clientName);

				updateClientEntry(rundata, clientEntry);

				Registry.addEntry(Registry.CLIENT, clientEntry);

				clearUserData(rundata);
			}
		}
		catch (EntityExistsException e)
		{
			//
			// dup key found - display error message - bring back to same screen
			//
			JetspeedLink link = JetspeedLinkFactory.getInstance(rundata);
			DynamicURI duri =
				link
					.getPaneByName(CLIENT_UPDATE_PANE)
					.addPathInfo(
						SecurityConstants.PARAM_MODE,
						SecurityConstants.PARAM_MODE_INSERT)
					.addPathInfo(
						SecurityConstants.PARAM_MSGID,
						SecurityConstants.MID_ENTITY_ALREADY_EXISTS);
			JetspeedLinkFactory.putInstance(link);
			rundata.setRedirectURI(duri.toString());

			resetForm(rundata);
		}
		catch (Exception e)
		{
			JetspeedLink link = JetspeedLinkFactory.getInstance(rundata);
			DynamicURI duri =
				link
					.getPaneByName(CLIENT_UPDATE_PANE)
					.addPathInfo(
						SecurityConstants.PARAM_MODE,
						SecurityConstants.PARAM_MODE_INSERT)
					.addPathInfo(
						SecurityConstants.PARAM_MSGID,
						SecurityConstants.MID_UPDATE_FAILED);
			JetspeedLinkFactory.putInstance(link);
			rundata.setRedirectURI(duri.toString());

			resetForm(rundata);
		}
	}

	/**
	 * Update a client entry
	 * @param rundata The turbine rundata context for this request.
	 * @param context The velocity context for this request.
	 * @throws Exception
	 */
	public void doUpdate(RunData rundata, Context context) throws Exception
	{
		try
		{
			String clientName =
				rundata.getParameters().getString("client_name");
			BaseClientEntry clientEntry =
				(BaseClientEntry) Registry.getEntry(
					Registry.CLIENT,
					clientName);
			if (clientEntry != null)
			{
				updateClientEntry(rundata, clientEntry);
				Registry.addEntry(Registry.CLIENT, clientEntry);
				clearUserData(rundata);
			}
			else
			{
				JetspeedLink link = JetspeedLinkFactory.getInstance(rundata);
				DynamicURI duri =
					link
						.getPaneByName(CLIENT_UPDATE_PANE)
						.addPathInfo(
							SecurityConstants.PARAM_MODE,
							SecurityConstants.PARAM_MODE_UPDATE)
						.addPathInfo(
							SecurityConstants.PARAM_MSGID,
							SecurityConstants.MID_INVALID_ENTITY_NAME);

				JetspeedLinkFactory.putInstance(link);
				rundata.setRedirectURI(duri.toString());

				resetForm(rundata);
			}
		}
		catch (Exception e)
		{
			JetspeedLink link = JetspeedLinkFactory.getInstance(rundata);
			DynamicURI duri =
				link
					.getPaneByName(CLIENT_UPDATE_PANE)
					.addPathInfo(
						SecurityConstants.PARAM_MODE,
						SecurityConstants.PARAM_MODE_UPDATE)
					.addPathInfo(
						SecurityConstants.PARAM_MSGID,
						SecurityConstants.MID_UPDATE_FAILED);
			JetspeedLinkFactory.putInstance(link);
			rundata.setRedirectURI(duri.toString());

			resetForm(rundata);
		}
	}

	/**
	 * Add a mimetype to a client entry
	 * @param rundata The turbine rundata context for this request.
	 * @param context The velocity context for this request.
	 * @throws Exception
	 */
	public void doAddmimetype(RunData rundata, Context context)
		throws Exception
	{
		try
		{
			String clientName =
				rundata.getParameters().getString("client_name");
			ClientEntry clientEntry =
				(ClientEntry) Registry.getEntry(Registry.CLIENT, clientName);
			if (clientEntry != null)
			{
				String mimeType = rundata.getParameters().getString("mimetype");
				clientEntry.getMimetypeMap().addMimetype(mimeType);

				Registry.addEntry(Registry.CLIENT, clientEntry);
				clearUserData(rundata);
			}
			else
			{
				JetspeedLink link = JetspeedLinkFactory.getInstance(rundata);
				DynamicURI duri =
					link
						.getPaneByName(CLIENT_UPDATE_PANE)
						.addPathInfo(
							SecurityConstants.PARAM_MODE,
							SecurityConstants.PARAM_MODE_UPDATE)
						.addPathInfo(
							SecurityConstants.PARAM_MSGID,
							SecurityConstants.MID_INVALID_ENTITY_NAME);

				JetspeedLinkFactory.putInstance(link);
				rundata.setRedirectURI(duri.toString());

				resetForm(rundata);
			}
		}
		catch (Exception e)
		{
			JetspeedLink link = JetspeedLinkFactory.getInstance(rundata);
			DynamicURI duri =
				link
					.getPaneByName(CLIENT_UPDATE_PANE)
					.addPathInfo(
						SecurityConstants.PARAM_MODE,
						SecurityConstants.PARAM_MODE_UPDATE)
					.addPathInfo(
						SecurityConstants.PARAM_MSGID,
						SecurityConstants.MID_UPDATE_FAILED);
			JetspeedLinkFactory.putInstance(link);
			rundata.setRedirectURI(duri.toString());

			resetForm(rundata);
		}
	}

	/**
	 * Remove mime types from a client entry
	 * @param rundata The turbine rundata context for this request.
	 * @param context The velocity context for this request.
	 * @throws Exception
	 */
	public void doRemovemimetype(RunData rundata, Context context)
		throws Exception
	{
		try
		{
			String clientName =
				rundata.getParameters().getString("client_name");
			ClientEntry clientEntry =
				(ClientEntry) Registry.getEntry(Registry.CLIENT, clientName);
			if (clientEntry != null)
			{
				String[] mimeTypes =
					rundata.getParameters().getStrings("mimetype");
				if (mimeTypes != null && mimeTypes.length > 0)
				{
					for (int i = 0; i < mimeTypes.length; i++)
					{
						String mimeType = mimeTypes[i];

						clientEntry.getMimetypeMap().removeMimetype(mimeType);
					}

					Registry.addEntry(Registry.CLIENT, clientEntry);
					clearUserData(rundata);
				}
			}
			else
			{
				JetspeedLink link = JetspeedLinkFactory.getInstance(rundata);
				DynamicURI duri =
					link
						.getPaneByName(CLIENT_UPDATE_PANE)
						.addPathInfo(
							SecurityConstants.PARAM_MODE,
							SecurityConstants.PARAM_MODE_UPDATE)
						.addPathInfo(
							SecurityConstants.PARAM_MSGID,
							SecurityConstants.MID_INVALID_ENTITY_NAME);

				JetspeedLinkFactory.putInstance(link);
				rundata.setRedirectURI(duri.toString());

				resetForm(rundata);
			}
		}
		catch (Exception e)
		{
			JetspeedLink link = JetspeedLinkFactory.getInstance(rundata);
			DynamicURI duri =
				link
					.getPaneByName(CLIENT_UPDATE_PANE)
					.addPathInfo(
						SecurityConstants.PARAM_MODE,
						SecurityConstants.PARAM_MODE_UPDATE)
					.addPathInfo(
						SecurityConstants.PARAM_MSGID,
						SecurityConstants.MID_UPDATE_FAILED);
			JetspeedLinkFactory.putInstance(link);
			rundata.setRedirectURI(duri.toString());

			resetForm(rundata);
		}
	}

	/**
	 * Add capabilities to a client entry
	 * @param rundata The turbine rundata context for this request.
	 * @param context The velocity context for this request.
	 * @throws Exception
	 */
	public void doAddcapability(RunData rundata, Context context)
		throws Exception
	{
		try
		{
			String clientName =
				rundata.getParameters().getString("client_name");
			ClientEntry clientEntry =
				(ClientEntry) Registry.getEntry(Registry.CLIENT, clientName);
			if (clientEntry != null)
			{
				String[] capabilities =
					rundata.getParameters().getStrings("capability");
				if (capabilities != null && capabilities.length > 0)
				{
					CapabilityMap cm = clientEntry.getCapabilityMap();
					for (int i = 0; i < capabilities.length; i++)
					{
						String capability = capabilities[i];
						if (cm.contains(capability))
						{
							Log.info(
								"Client entry "
									+ clientName
									+ "already contains capabillity "
									+ capability);
						}
						else
						{
							if(capability != null && capability.length() > 0)
							{
								cm.addCapability(capability);
							}
						}
					}
				}

				Registry.addEntry(Registry.CLIENT, clientEntry);
				clearUserData(rundata);
			}
			else
			{
				JetspeedLink link = JetspeedLinkFactory.getInstance(rundata);
				DynamicURI duri =
					link
						.getPaneByName(CLIENT_UPDATE_PANE)
						.addPathInfo(
							SecurityConstants.PARAM_MODE,
							SecurityConstants.PARAM_MODE_UPDATE)
						.addPathInfo(
							SecurityConstants.PARAM_MSGID,
							SecurityConstants.MID_INVALID_ENTITY_NAME);

				JetspeedLinkFactory.putInstance(link);
				rundata.setRedirectURI(duri.toString());

				resetForm(rundata);
			}
		}
		catch (Exception e)
		{
			JetspeedLink link = JetspeedLinkFactory.getInstance(rundata);
			DynamicURI duri =
				link
					.getPaneByName(CLIENT_UPDATE_PANE)
					.addPathInfo(
						SecurityConstants.PARAM_MODE,
						SecurityConstants.PARAM_MODE_UPDATE)
					.addPathInfo(
						SecurityConstants.PARAM_MSGID,
						SecurityConstants.MID_UPDATE_FAILED);
			JetspeedLinkFactory.putInstance(link);
			rundata.setRedirectURI(duri.toString());

			resetForm(rundata);
		}
	}

	/**
	 * Remove capabilites from a client entry
	 * @param rundata The turbine rundata context for this request.
	 * @param context The velocity context for this request.
	 * @throws Exception
	 */
	public void doRemovecapability(RunData rundata, Context context)
		throws Exception
	{
		try
		{
			String clientName =
				rundata.getParameters().getString("client_name");
			ClientEntry clientEntry =
				(ClientEntry) Registry.getEntry(Registry.CLIENT, clientName);
			if (clientEntry != null)
			{
				String[] capabilities =
					rundata.getParameters().getStrings("capability");
				if (capabilities != null && capabilities.length > 0)
				{
					for (int i = 0; i < capabilities.length; i++)
					{
						String capability = capabilities[i];

						clientEntry.getCapabilityMap().removeCapability(
							capability);
					}

					Registry.addEntry(Registry.CLIENT, clientEntry);
					clearUserData(rundata);
				}
			}
			else
			{
				JetspeedLink link = JetspeedLinkFactory.getInstance(rundata);
				DynamicURI duri =
					link
						.getPaneByName(CLIENT_UPDATE_PANE)
						.addPathInfo(
							SecurityConstants.PARAM_MODE,
							SecurityConstants.PARAM_MODE_UPDATE)
						.addPathInfo(
							SecurityConstants.PARAM_MSGID,
							SecurityConstants.MID_INVALID_ENTITY_NAME);

				JetspeedLinkFactory.putInstance(link);
				rundata.setRedirectURI(duri.toString());

				resetForm(rundata);
			}
		}
		catch (Exception e)
		{
			JetspeedLink link = JetspeedLinkFactory.getInstance(rundata);
			DynamicURI duri =
				link
					.getPaneByName(CLIENT_UPDATE_PANE)
					.addPathInfo(
						SecurityConstants.PARAM_MODE,
						SecurityConstants.PARAM_MODE_UPDATE)
					.addPathInfo(
						SecurityConstants.PARAM_MSGID,
						SecurityConstants.MID_UPDATE_FAILED);
			JetspeedLinkFactory.putInstance(link);
			rundata.setRedirectURI(duri.toString());

			resetForm(rundata);
		}
	}

	/**
	 * Set the client entry parameters from the input parameters
	 * @param rundata The turbine rundata context for this request.
	 * @param context The velocity context for this request.
	 */
	private void updateClientEntry(
		RunData rundata,
		BaseClientEntry clientEntry)
	{
		String userAgentPattern =
			rundata.getParameters().getString("user_agent_pattern");
		String manufacturer = rundata.getParameters().getString("manufacturer");
		String model = rundata.getParameters().getString("model");
		String version = rundata.getParameters().getString("version");
		boolean hidden = rundata.getParameters().getBoolean("hidden", false);

		clientEntry.setUseragentpattern(userAgentPattern);
		clientEntry.setManufacturer(manufacturer);
		clientEntry.setModel(model);
		clientEntry.setVersion(version);
		clientEntry.setHidden(hidden);
	}

	/**
	 * Delete a client entry from the registry
	 * @param rundata The turbine rundata context for this request.
	 * @param context The velocity context for this request.
	 * @throws Exception
	 */
	public void doDelete(RunData rundata, Context context) throws Exception
	{
		try
		{
			String clientName =
				rundata.getParameters().getString("client_name");

			if (clientName == null || clientName.length() == 0)
			{
				JetspeedLink link = JetspeedLinkFactory.getInstance(rundata);
				DynamicURI duri =
					link
						.getPaneByName(CLIENT_UPDATE_PANE)
						.addPathInfo(
							SecurityConstants.PARAM_MODE,
							SecurityConstants.PARAM_MODE_DELETE)
						.addPathInfo(
							SecurityConstants.PARAM_MSGID,
							SecurityConstants.MID_INVALID_ENTITY_NAME);
				JetspeedLinkFactory.putInstance(link);
				rundata.setRedirectURI(duri.toString());

				resetForm(rundata);
			}
			else
			{
				Registry.removeEntry(Registry.CLIENT, clientName);
				clearUserData(rundata);
			}
		}
		catch (Exception e)
		{
                        Log.error(e);
			JetspeedLink link = JetspeedLinkFactory.getInstance(rundata);
			DynamicURI duri =
				link
					.getPaneByName(CLIENT_UPDATE_PANE)
					.addPathInfo(
						SecurityConstants.PARAM_MODE,
						SecurityConstants.PARAM_MODE_DELETE)
					.addPathInfo(
						SecurityConstants.PARAM_MSGID,
						SecurityConstants.MID_DELETE_FAILED);
			JetspeedLinkFactory.putInstance(link);
			rundata.setRedirectURI(duri.toString());
		}
	}

	/**
	 * Cleanup method
	 * @param rundata The turbine rundata context for this request.
	 * @param context The velocity context for this request.
	 * @throws Exception
	 */
	public void doCancel(RunData rundata, Context context) throws Exception
	{
		clearUserData(rundata);
	}

	/**
	 * Populates the user's temp storage with form data
	 * @param rundata The turbine rundata context for this request.
	 */
	private void resetForm(RunData rundata)
	{
		String clientName = rundata.getParameters().getString("client_name");
		String userAgentPattern =
			rundata.getParameters().getString("user_agent_pattern");
		String manufacturer = rundata.getParameters().getString("manufacturer");
		String model = rundata.getParameters().getString("model");
		String version = rundata.getParameters().getString("version");
		String hidden = rundata.getParameters().getString("hidden");

		String capability = rundata.getParameters().getString("capability");
		String mimeType = rundata.getParameters().getString("mimetype");

		rundata.getUser().setTemp("client_name", clientName);
		rundata.getUser().setTemp("user_agent_pattern", userAgentPattern);
		rundata.getUser().setTemp("manufacturer", manufacturer);
		rundata.getUser().setTemp("model", model);
		rundata.getUser().setTemp("version", version);
		rundata.getUser().setTemp("hidden", hidden);

		rundata.getUser().setTemp("capability", capability);
		rundata.getUser().setTemp("mimetype", mimeType);
	}

	/**
	 * Clears the temporary storage of any data that was used
	 * @param rundata The turbine rundata context for this request.
	 */
	private void clearUserData(RunData rundata)
	{
		try
		{
			rundata.getUser().removeTemp("client_name");
			rundata.getUser().removeTemp("user_agent_pattern");
			rundata.getUser().removeTemp("manufacturer");
			rundata.getUser().removeTemp("model");
			rundata.getUser().removeTemp("version");
			rundata.getUser().removeTemp("hidden");

			rundata.getUser().removeTemp("capability");
			rundata.getUser().removeTemp("mimetype");
		}
		catch (Exception e)
		{
			if (Log.getLogger().isDebugEnabled())
			{
				Log.debug("ClientUpdateAction: Failed to clear user data");
			}
		}
	}
}
