/*
 * Copyright (C) 2004 Red Hat Inc. All Rights Reserved.
 *
 * The contents of this file are subject to the CCM 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.redhat.com/licenses/ccmpl.html.
 *
 * 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.cms.ui.category;

import com.arsdigita.bebop.FormProcessException;
import com.arsdigita.bebop.PageState;
import com.arsdigita.bebop.SingleSelectionModel;
import com.arsdigita.bebop.event.FormProcessListener;
import com.arsdigita.bebop.event.FormSectionEvent;
import com.arsdigita.bebop.event.ParameterEvent;
import com.arsdigita.bebop.parameters.GlobalizedParameterListener;
import com.arsdigita.bebop.parameters.ParameterData;
import com.arsdigita.categorization.Category;
import com.arsdigita.cms.CMS;
import com.arsdigita.cms.ContentSection;
import com.arsdigita.cms.SecurityManager;
import com.arsdigita.cms.ui.BaseForm;
import com.arsdigita.cms.util.GlobalizationUtil;
import com.arsdigita.globalization.GlobalizedMessage;
import com.arsdigita.kernel.permissions.ObjectPermissionCollection;
import com.arsdigita.kernel.permissions.PermissionDescriptor;
import com.arsdigita.kernel.permissions.PermissionService;
import org.apache.log4j.Logger;


/**
 * @author Scott Seago
 * @version $Id: //cms/dev/src/com/arsdigita/cms/ui/category/AddUseContextForm.java#4 $
 */
class AddUseContextForm extends BaseForm {
    public static final String versionId =
        "$Id: //cms/dev/src/com/arsdigita/cms/ui/category/AddUseContextForm.java#4 $" +
        "$Author: dennis $" +
        "$DateTime: 2004/04/07 16:07:11 $";

    private static final Logger s_log = Logger.getLogger(AddUseContextForm.class);

    private final SingleSelectionModel m_model;

    private final Name m_useContext;
    private final Name m_rootName;
    private final Description m_rootDescription;

    AddUseContextForm(final SingleSelectionModel model) {
        super("useContext", gz("cms.ui.category.add_use_context"));

        m_model = model;
        m_useContext = new Name("useContext", 200, true);
        addField(gz("cms.ui.category.use_context"), m_useContext);
        m_rootName = new Name("rootName", 200, true);
        addField(gz("cms.ui.name"), m_rootName);
        m_rootDescription = new Description("rootName", 200, true);
        addField(gz("cms.ui.description"), m_rootDescription);

        addAction(new Finish());
        addAction(new Cancel());

        addSecurityListener(SecurityManager.CATEGORY_ADMIN);
        m_useContext.addValidationListener(new ValidationListener());

        addProcessListener(new ProcessListener());
    }

    private class ValidationListener extends GlobalizedParameterListener {
        public ValidationListener() {
            super();
            setError(GlobalizationUtil.globalize("cms.ui.category.use_context_must_be_unique"));
        }

        public final void validate(final ParameterEvent e)
                throws FormProcessException {

            ParameterData data = e.getParameterData();

            final String name = (String) m_useContext.getValue(e.getPageState());
            if (Category.getRootForObject(CMS.getContext().getContentSection(),
                                          name) != null) {
                data.addError(getError());
            }
        }
    }
    private class ProcessListener implements FormProcessListener {
        public final void process(final FormSectionEvent e)
                throws FormProcessException {
            final PageState state = e.getPageState();

            final String useContext = (String) m_useContext.getValue(state);

            final String rootName = (String) m_rootName.getValue(state);
            final String rootDescription = (String) m_rootDescription.getValue(state);
            Category root = new Category();
            root.setName(rootName);
            root.setDescription(rootDescription);
            root.setAbstract(true);
            
            final ContentSection section =
                CMS.getContext().getContentSection();

            Category.setRootForObject(section, root, useContext);
            PermissionService.setContext(root, section);
            Category defaultRoot = Category.getRootForObject(section);
            if (defaultRoot != null) {
                ObjectPermissionCollection coll = 
                    PermissionService.getDirectGrantedPermissions(defaultRoot.getOID());
                while (coll.next()) {
                    PermissionService.grantPermission(new PermissionDescriptor(coll.getPrivilege(), 
                                                                               root.getOID(), 
                                                                               coll.getGranteeOID()));
                }

            }
            m_model.setSelectedKey(state, useContext == null ? 
                                   CategoryUseContextModelBuilder.DEFAULT_USE_CONTEXT :
                                   useContext);
        }
    }
}
