/*
 * Copyright (C) 2001-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.ui.login;

import com.arsdigita.web.Web;
import com.arsdigita.kernel.User;
import com.arsdigita.kernel.security.UserContext;
import com.arsdigita.bebop.FormData;
import com.arsdigita.bebop.event.FormInitListener;
import com.arsdigita.bebop.event.FormSectionEvent;
import com.arsdigita.bebop.parameters.EmailParameter;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import org.apache.log4j.Logger;

/**
 * Initializes the value of the given parameter to the current user's email
 * address.  If the user is not logged in or the email address is invalid,
 * the parameter is not modified.
 *
 * @author Sameer Ajmani
 **/
public class EmailInitListener implements FormInitListener {
    public static final String versionId =
        "$Id: //core-platform/dev/src/com/arsdigita/ui/login/EmailInitListener.java#13 $" +
        "$Author: dennis $" +
        "$DateTime: 2004/04/07 16:07:11 $";

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

    private EmailParameter m_param;

    public EmailInitListener(EmailParameter param) {
        m_param = param;
    }

    public void init(FormSectionEvent event) {
        FormData data = event.getFormData();

        s_log.debug("START");

        UserContext ctx = Web.getUserContext();

        if (!ctx.isLoggedIn()) {
            s_log.debug("FAILURE not logged in");
            return;
        }

        User  user = ctx.getUser();

        if (user == null) {
            s_log.debug("FAILURE no such user");
            return;
        }

        if (user.getPrimaryEmail() == null) {
            s_log.debug("FAILURE null primary email");
            return;
        }

        if (user.getPrimaryEmail().getEmailAddress() == null) {
            s_log.debug("FAILURE null email address");
            return;
        }

        try {
            InternetAddress addr = new InternetAddress
                (user.getPrimaryEmail().getEmailAddress());
            data.put(m_param.getName(), addr);
        } catch (AddressException e) {
            s_log.debug("FAILURE badly formed address");
            return;
        }

        s_log.debug("SUCCESS");
    }
}
