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


import com.arsdigita.cms.CMS;
import com.arsdigita.cms.ContentPage;
import com.arsdigita.cms.util.GlobalizationUtil;
import com.arsdigita.search.ContentType;
import com.arsdigita.search.ContentProvider;

import com.arsdigita.domain.DomainObjectXMLRenderer;
import com.arsdigita.xml.Document;
import com.arsdigita.xml.Element;
import com.arsdigita.util.UncheckedWrapperException;

import org.apache.log4j.Logger;

public class ContentPageXMLContentProvider implements ContentProvider {

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

    private ContentPage m_page;
    private String m_context;

    public ContentPageXMLContentProvider(String context,
                                         ContentPage page) {
        m_context = context;
        m_page = page;
    }

    public String getContext() {
        return m_context;
    }

    public ContentType getType() {
        return ContentType.XML;
    }

    public byte[] getBytes() {
        
        Element root = new Element("cms:item", CMS.CMS_XML_NS);
        DomainObjectXMLRenderer renderer =
            new DomainObjectXMLRenderer(root);

        renderer.setWrapAttributes(true);
        renderer.walk(m_page, ContentPageMetadataProvider.class.getName());

        Document doc = null;
        try {
            doc = new Document(root);
        } catch (javax.xml.parsers.ParserConfigurationException ex) {
            final String message =
                (String) GlobalizationUtil.globalize
                    ("cms.cannot_create_xml_document").localize();
            throw new UncheckedWrapperException(message,  ex);
        }
        if (s_log.isDebugEnabled()) {
            s_log.debug("XML is " + doc.toString(true));
        }

        // Hmm, why on earth doesn't this method return
        // Element directly ?!?!
        String xml = doc.toString(true);
        return xml.getBytes();
    }

}
