/*
 * Copyright (C) 2002-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.formbuilder.actions;

import com.arsdigita.formbuilder.util.Placeholders;

import com.arsdigita.persistence.OID;
import com.arsdigita.persistence.DataObject;
import com.arsdigita.persistence.metadata.ObjectType;
import com.arsdigita.domain.DataObjectNotFoundException;

import com.arsdigita.bebop.FormData;
import com.arsdigita.bebop.FormProcessException;
import com.arsdigita.bebop.event.FormSectionEvent;

import com.arsdigita.mail.Mail;

import com.arsdigita.formbuilder.PersistentProcessListener;
import com.arsdigita.formbuilder.util.Placeholders;

import java.math.BigDecimal;
import java.util.Iterator;

import javax.mail.MessagingException;
import com.arsdigita.util.UncheckedWrapperException;
import com.arsdigita.bebop.event.FormProcessListener;

public class XMLEmailListener extends PersistentProcessListener {
    public static final String BASE_DATA_OBJECT_TYPE =
        "com.arsdigita.formbuilder.actions.XMLEmailListener";

    public static final String TO = "recipient";
    public static final String SUBJECT = "subject";

    public XMLEmailListener() {
        this(BASE_DATA_OBJECT_TYPE);
    }

    public XMLEmailListener(String typeName) {
        super(typeName);
    }

    public XMLEmailListener(ObjectType type) {
        super(type);
    }

    public XMLEmailListener(DataObject obj) {
        super(obj);
    }

    public XMLEmailListener(BigDecimal id)
        throws DataObjectNotFoundException {

        this(new OID(BASE_DATA_OBJECT_TYPE, id));
    }

    public XMLEmailListener(OID oid)
        throws DataObjectNotFoundException {

        super(oid);
    }


    public static XMLEmailListener create(String name,
                                          String description,
                                          String to,
                                          String subject) {
        XMLEmailListener l = new XMLEmailListener();
        l.setup(name, description, to, subject);
        return l;
    }

    protected void setup(String name,
                         String description,
                         String to,
                         String subject) {
        super.setup(name, description);
        set(TO, to);
        set(SUBJECT, subject);
    }

    // XXX hack to get around some wierd issues
    // with mdsql associations where the object
    // type in question is a subtype of the
    // one named in the association definition
    public boolean isContainerModified() {
        return false;
    }

    public String getTo() {
        return (String)get(TO);
    }

    public void setTo(String to) {
        set(TO, to);
    }

    public String getSubject() {
        return (String)get(SUBJECT);
    }

    public void setSubject(String subject) {
        set(SUBJECT, subject);
    }

    public FormProcessListener createProcessListener() {
        return new XMLEmailProcessListener(getTo(),
                                           getSubject());
    }

    private class XMLEmailProcessListener implements FormProcessListener {
        String m_to;
        String m_subject;

        public XMLEmailProcessListener(String to,
                                       String subject) {
            m_to = to;
            m_subject = subject;
        }

        public void process(FormSectionEvent e)
            throws FormProcessException {
            
            Placeholders p = new Placeholders(e.getPageState());

            String to = p.interpolate(m_to);
            String subject = p.interpolate(m_subject);
            //String from = p.interpolate("::user.givenname:: ::user.familyname:: <::user.email::>");
            String from = p.interpolate("::user.email::");

            StringBuffer body = new StringBuffer(p.interpolate("<form-data>\n  <from email=\"::user.email::\">\n    <givenname>::user.givenname::</givename>    <familyname>::user.familyname::</familyname>\n  </from>\n  <field-list>\n"));

            FormData data = e.getFormData();
            Iterator keys = data.keySet().iterator();
            while (keys.hasNext()) {
                String key = (String)keys.next();
                Object value = data.get(key);

                body.append("  <field" + (value == null ? "" : (" type=\"" + value.getClass().getName() + "\"")) + "><key>" + key + "</key>" + (value == null ? "" : "<value>" + value.toString() + "</value>") + "</field>\n");
            }
            body.append("</field-list>\n</form-data>\n");

            try {
                Mail message = new Mail(to, from, subject, body.toString());
                message.send();
            } catch (MessagingException ex) {
                throw new UncheckedWrapperException("cannot send message", ex);
            }
        }
    }
}
