/*
 * Copyright (C) 2003-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.role;

import com.arsdigita.bebop.FormProcessException;
import com.arsdigita.bebop.PageState;
import com.arsdigita.bebop.event.ParameterEvent;
import com.arsdigita.bebop.event.ParameterListener;
import com.arsdigita.bebop.event.PrintEvent;
import com.arsdigita.bebop.event.PrintListener;
import com.arsdigita.bebop.form.CheckboxGroup;
import com.arsdigita.bebop.form.Option;
import com.arsdigita.cms.CMS;
import com.arsdigita.cms.ContentSection;
import com.arsdigita.cms.ui.BaseForm;
import com.arsdigita.globalization.GlobalizedMessage;
import com.arsdigita.kernel.Role;
import com.arsdigita.kernel.RoleCollection;
import com.arsdigita.persistence.DataQuery;
import com.arsdigita.persistence.SessionManager;
import com.arsdigita.util.UncheckedWrapperException;
import org.apache.log4j.Logger;

import java.util.TooManyListenersException;

/**
 * @author Justin Ross &lt;jross@redhat.com&gt;
 * @version $Id: //cms/dev/src/com/arsdigita/cms/ui/role/BaseRoleForm.java#10 $
 */
public class BaseRoleForm extends BaseForm {
    public static final String versionId =
        "$Id: //cms/dev/src/com/arsdigita/cms/ui/role/BaseRoleForm.java#10 $" +
        "$Author: dennis $" +
        "$DateTime: 2004/04/07 16:07:11 $";

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

    final Name m_name;
    final Description m_description;
    CheckboxGroup m_privileges;

    private boolean m_useViewersGroup;

    public BaseRoleForm(final String key,
                        final GlobalizedMessage message,
                        final boolean useViewersGroup) {
        super(key, message);

        m_useViewersGroup = useViewersGroup;

        m_name = new Name("label", 200, true);
        addField(gz("cms.ui.name"), m_name);

        m_description = new Description("description", 4000, false);
        addField(gz("cms.ui.description"), m_description);

        m_privileges = new CheckboxGroup("privileges");
        addField(gz("cms.ui.role.privileges"), m_privileges);

        try {
            m_privileges.addPrintListener(new PrivilegePrinter());
        } catch (TooManyListenersException tmle) {
            throw new UncheckedWrapperException(tmle);
        }

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

        addSecurityListener(STAFF_ADMIN);
    }

    private class PrivilegePrinter implements PrintListener {
        public final void prepare(final PrintEvent e) {
            final CheckboxGroup target = (CheckboxGroup) e.getTarget();
            final PageState state = e.getPageState();

            final DataQuery query = SessionManager.getSession().retrieveQuery
                (RoleFactory.CMS_PRIVILEGES);
            query.addOrder(RoleFactory.SORT_ORDER);

            while (query.next()) {
                target.addOption
                    (new Option((String) query.get(RoleFactory.PRIVILEGE),
                                (String) query.get(RoleFactory.PRETTY_NAME)));
            }

            query.close();
        }
    }

    class NameUniqueListener implements ParameterListener {
        private final RoleRequestLocal m_role;

        NameUniqueListener(final RoleRequestLocal role) {
            m_role = role;
        }

        public final void validate(final ParameterEvent e)
                throws FormProcessException {
            final PageState state = e.getPageState();
            final ContentSection section =
                CMS.getContext().getContentSection();
            final String name = (String) m_name.getValue(state);

            RoleCollection roles;

            if (m_useViewersGroup) {
                roles = section.getViewersGroup().getRoles();
            } else {
                roles = section.getStaffGroup().getRoles();
            }

            while (roles.next()) {
                final Role role = roles.getRole();

                if (roles.getRole().getName().equalsIgnoreCase(name)
                        && (m_role == null
                            || !m_role.getRole(state).equals(role))) {
                    roles.close();

                    throw new FormProcessException
                        (lz("cms.ui.role.name_not_unique"));
                }
            }

            roles.close();
        }
    }
}
