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

import com.arsdigita.persistence.metadata.Property;
import com.arsdigita.xml.Formatter;
import com.arsdigita.xml.XML;

import java.util.Map;
import java.util.HashMap;

import org.apache.log4j.Logger;

public class SimpleDomainObjectXMLFormatter 
    implements DomainObjectXMLFormatter {
    
    private static final Logger s_log = 
        Logger.getLogger(SimpleDomainObjectXMLFormatter.class);

    private Map m_formatters = new HashMap();

    public void addFormatter(String property,
                             Formatter formatter) {
        if (s_log.isDebugEnabled()) {
            s_log.debug("Adding formatter for " + property +
                        ": " + formatter.getClass());
        }
        m_formatters.put(property, formatter);
    }

    public String format(DomainObject obj,
                         String path,
                         Property prop,
                         Object value) {
        Formatter formatter = (Formatter)m_formatters.get(path);
        if (formatter == null) {
            if (s_log.isDebugEnabled()) {
                s_log.debug("No formatter for " + path + 
                            " using default");
            }
            return XML.format(value);
        }
        if (s_log.isDebugEnabled()) {
            s_log.debug("Processing property " + path + 
                        " with " + formatter.getClass());
        }
        return formatter.format(value);
    }

}
