/*
 * 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.FormData;
import com.arsdigita.bebop.FormProcessException;
import com.arsdigita.bebop.PageState;
import com.arsdigita.bebop.SingleSelectionModel;
import com.arsdigita.bebop.event.FormSectionEvent;
import com.arsdigita.bebop.form.TextField;
import com.arsdigita.cms.ui.FormSecurityListener;
import com.arsdigita.cms.ui.UserAddForm;
import com.arsdigita.cms.util.GlobalizationUtil;
import com.arsdigita.cms.util.SecurityConstants;
import com.arsdigita.domain.DataObjectNotFoundException;
import com.arsdigita.kernel.Group;
import com.arsdigita.kernel.Role;
import com.arsdigita.kernel.User;
import com.arsdigita.kernel.permissions.PermissionDescriptor;
import com.arsdigita.kernel.permissions.PermissionService;
import com.arsdigita.kernel.permissions.PrivilegeDescriptor;
import com.arsdigita.persistence.DataQuery;
import com.arsdigita.persistence.Filter;
import com.arsdigita.persistence.Session;
import com.arsdigita.persistence.SessionManager;
import com.arsdigita.util.Assert;

import java.math.BigDecimal;

/**
 * @author Michael Pih
 * @author Uday Mathur
 * @version $Id: //cms/dev/src/com/arsdigita/cms/ui/role/RoleAdminAddForm.java#7 $
 */
class RoleAdminAddForm extends UserAddForm {
    public static final String versionId =
        "$Id: //cms/dev/src/com/arsdigita/cms/ui/role/RoleAdminAddForm.java#7 $" +
        "$Author: dennis $" +
        "$DateTime: 2004/04/07 16:07:11 $";

    private final SingleSelectionModel m_roles;

    private static final String NAME_FILTER = 
        "(upper(lastName) like ('%' || upper(:search) || '%'))" +
        " or " +
        "(upper(firstName) like ('%' || upper(:search) || '%'))" +
        " or " +
        "(upper(email) like ('%' || upper(:search) || '%'))";

    public RoleAdminAddForm(SingleSelectionModel roles, TextField search) {
        super(search, "RoleAddAdmin");

        m_roles = roles;

        getForm().addSubmissionListener
            (new FormSecurityListener(SecurityConstants.STAFF_ADMIN));
    }

    protected DataQuery makeQuery(PageState s) {
        Assert.truth(m_roles.isSelected(s));

        Session session = SessionManager.getSession();

        // XXX: Figure out how to use role directly here
        DataQuery dq =
            session.retrieveQuery("com.arsdigita.cms.roleAdminUserSearch");

        BigDecimal roleId = new BigDecimal((String) m_roles.getSelectedKey(s));
        String searchQuery = (String) getSearchWidget().getValue(s);

        makeFilter(dq, roleId, searchQuery);
        dq.addOrder("upper(lastName), upper(firstName), upper(email)");
        return dq;
    }

    /**
     * Filters out members of the current group and users whose name or email
     * address matches the search string.
     */
    private void makeFilter(DataQuery dq, BigDecimal roleId, String search) {
        dq.setParameter("excludedRoleId", roleId);

        // Add the search filter if the search query is not null.
        if ( search != null ) {
            dq.clearFilter();
            Filter filter = dq.addFilter(NAME_FILTER);
            filter.set("search", search);
        }
    }

    public void process(FormSectionEvent event) throws FormProcessException {
        FormData data = event.getFormData();
        PageState state = event.getPageState();
        Assert.truth(m_roles.isSelected(state));

        String[] users = (String[]) data.get("users");
        if ( users != null ) {

            BigDecimal roleId =
                new BigDecimal((String) m_roles.getSelectedKey(state));

            Role role = null;
            try {
                role = new Role(roleId);
            } catch (DataObjectNotFoundException e) {
                e.printStackTrace();
                throw new FormProcessException(e.getMessage());
            }

            Group group = role.getGroup();

            // Add each checked user to the role
            try {
                User user;
                for ( int i = 0; i < users.length; i++ ) {

                    user = User.retrieve(new BigDecimal(users[i]));

                    PermissionDescriptor perm =
                        new PermissionDescriptor(PrivilegeDescriptor.ADMIN,
                                                 group,
                                                 user);

                    // double click protection
                    if ( !PermissionService.checkPermission(perm) ) {
                        PermissionService.grantPermission(perm);
                    }
                }
                role.save();

            } catch (DataObjectNotFoundException e) {
                throw new FormProcessException( (String) GlobalizationUtil.globalize("cms.ui.staff.cannot_add_user").localize(),  e);
            }

        } else {
            throw new FormProcessException( (String) GlobalizationUtil.globalize("cms.ui.staff.no_users_were_selected").localize());
        }

        fireCompletionEvent(state);
    }
}
