/*
 * Copyright (C) 2001 ArsDigita Corporation. All Rights Reserved.
 *
 * The contents of this file are subject to the ArsDigita Public 
 * License (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of
 * the License at http://www.arsdigita.com/ADPL.txt
 *
 * Software distributed under the License is distributed on an "AS
 * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * rights and limitations under the License.
 *
 */

package com.arsdigita.london.portal.ui;

import com.arsdigita.bebop.Component;
import com.arsdigita.bebop.Container;
import com.arsdigita.bebop.PageState;
import com.arsdigita.bebop.RequestLocal;
import com.arsdigita.bebop.event.ActionEvent;
import com.arsdigita.bebop.event.ActionListener;
import com.arsdigita.dispatcher.AccessDeniedException;
import com.arsdigita.kernel.Kernel;
import com.arsdigita.kernel.Party;
import com.arsdigita.london.portal.Workspace;
import com.arsdigita.toolbox.ui.SecurityContainer;
import com.arsdigita.web.LoginSignal;

public class PackageWorkspace extends WorkspaceComponent {

	private RequestLocal m_isAdmin = new RequestLocal();

	public PackageWorkspace() {
		super(new PackageWorkspaceSelectionModel());

		addCustomizeListener(new CustomizeListener());
	}

	protected void addCustomizeLinks(Container parent, Component child) {
		Container secure = new WorkspaceSecurityContainer(child);
		super.addCustomizeLinks(parent, secure);
	}

	private class CustomizeListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			PageState state = e.getPageState();

			Workspace workspace = getWorkspaceModel().getSelectedWorkspace(
					state);

			Party party = Kernel.getContext().getParty();
			if (party == null) {
				throw new LoginSignal(state.getRequest());
			}

			if (!PortalHelper.canCustomize(party, workspace)) {
				throw new AccessDeniedException(
						"no permission to customize workspace");
			}
		}
	}

	private class WorkspaceSecurityContainer extends SecurityContainer {

		public WorkspaceSecurityContainer(Component c) {
			super(c);
		}

		protected boolean canAccess(Party party, PageState state) {
			Boolean isAdmin = (Boolean) m_isAdmin.get(state);
			if (isAdmin == null) {
				Workspace workspace = getWorkspaceModel().getSelectedWorkspace(
						state);
				boolean canAccess = PortalHelper.canCustomize(party, workspace);
				isAdmin = new Boolean(canAccess);
				m_isAdmin.set(state, isAdmin);
			}
			return isAdmin.booleanValue();
		}
	}
}
