/*
 * 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.workflow;

import com.arsdigita.bebop.FormData;
import com.arsdigita.bebop.FormProcessException;
import com.arsdigita.bebop.PageState;
import com.arsdigita.bebop.SimpleContainer;
import com.arsdigita.bebop.event.FormSectionEvent;
import com.arsdigita.bebop.form.Submit;
import com.arsdigita.cms.CMS;
import com.arsdigita.cms.ui.UserAddForm;
import com.arsdigita.cms.ui.UserSearchForm;
import com.arsdigita.cms.util.GlobalizationUtil;
import com.arsdigita.globalization.GlobalizedMessage;
import com.arsdigita.kernel.User;
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.OID;
import com.arsdigita.persistence.Session;
import com.arsdigita.persistence.SessionManager;
import com.arsdigita.workflow.simple.UserTask;
import com.arsdigita.xml.Element;
import org.apache.log4j.Logger;

import java.math.BigDecimal;

/**
 * Contains forms to search and add users as Task Assignees.
 *
 * @author Uday Mathur
 * @author <a href="mailto:pihman@arsdigita.com">Michael Pih</a>
 * @version $Revision: #7 $ $Date: 2004/04/07 $
 */
class TaskAddUser extends SimpleContainer {
    public static final String versionId =
        "$Id: //cms/dev/src/com/arsdigita/cms/ui/workflow/TaskAddUser.java#7 $" +
        "$Author: dennis $" +
        "$DateTime: 2004/04/07 16:07:11 $";

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

    private final TaskRequestLocal m_task;

    private SearchForm m_search;
    private AddForm m_add;

    public TaskAddUser(final TaskRequestLocal task) {
        super();

        m_task = task;

        m_search = new SearchForm();
        add(m_search);

        m_add = new AddForm();
        add(m_add);
    }

    UserSearchForm getSearchForm() {
        return m_search;
    }

    UserAddForm getAddForm() {
        return m_add;
    }

    public final void generateXML(final PageState state,
                                  final Element parent) {
        if (isVisible(state)) {
            final FormData one = m_search.getFormData(state);
            final FormData two = m_add.getForm().getFormData(state);

            if (one != null && (one.isSubmission() || two.isSubmission())) {
                m_search.generateXML(state, parent);
                m_add.generateXML(state, parent);
            } else {
                m_search.generateXML(state, parent);
            }
        }
    }

    private static class SearchForm extends UserSearchForm {
        private final Submit m_cancel;

        public SearchForm() {
            super("user-search");

            m_cancel = new Submit("cancel", gz("cms.ui.cancel"));

            add(m_cancel);
        }
    }

    private class AddForm extends UserAddForm {
        public AddForm() {
            super(m_search.getSearchWidget());
        }

        protected final DataQuery makeQuery(final PageState state) {
            final Session session = SessionManager.getSession();

            final DataQuery query = session.retrieveQuery
                ("com.arsdigita.cms.workflow.searchToAddMembers");
            final String search = (String) getSearchWidget().getValue(state);

            makeFilter(query, search);
            query.addOrder("lastName, firstName, email");

            final OID oid = CMS.getContext().getContentSection().getOID();

            PermissionService.objectFilterQuery
                (query, "userId", PrivilegeDescriptor.READ, oid);

            return query;
        }

        private void makeFilter(final DataQuery query, final String search) {
            query.clearFilter();

            final Filter filter = query.addFilter
                ("upper(firstName || lastName || email) " +
                 "like '%' || upper(:search) || '%'");

            filter.set("search", search);
        }

        public final void process(final FormSectionEvent e)
                throws FormProcessException {
            final FormData data = e.getFormData();
            final PageState state = e.getPageState();

            final String[] users = (String[]) data.get("users");

            if (users == null) {
                throw new FormProcessException
                    (lz("cms.ui.workflow.no_users_were_selected"));
            } else {
                // Add each checked user to the task.

                final UserTask task = m_task.getTask(state);
                User user;

                for (int i = 0; i < users.length; i++) {
                    user = User.retrieve(new BigDecimal(users[i]));

                    // MP: Do double click protection here.

                    task.assignUser(user);
                }

                task.save();
            }
        }
    }

    private static GlobalizedMessage gz(final String key) {
        return GlobalizationUtil.globalize(key);
    }

    private static String lz(final String key) {
        return (String) gz(key).localize();
    }
}
