/*!
 * This method copies the selection defined by pDocRange to ODT format
 * placed in the ByteBuf bufODT
 */
UT_Error IE_Exp_OpenDocument::copyToBuffer(PD_DocumentRange * pDocRange,UT_ByteBuf *  bufODT)
{
    //
    // First export selected range to a tempory document
    //
    PD_Document * outDoc = new PD_Document();
    outDoc->createRawDocument();
    IE_Exp_DocRangeListener * pRangeListener = new IE_Exp_DocRangeListener(pDocRange,outDoc);
    UT_DEBUGMSG(("DocumentRange low %d High %d \n",pDocRange->m_pos1,pDocRange->m_pos2));
    PL_ListenerCoupleCloser* pCloser = new PL_ListenerCoupleCloser();
    pDocRange->m_pDoc->tellListenerSubset(pRangeListener,pDocRange,pCloser);
    if( pCloser)
        delete pCloser;
    
    //
    // Grab the RDF triples while we are copying...
    //
    if( PD_DocumentRDFHandle outrdf = outDoc->getDocumentRDF() )
    {

        std::set< std::string > xmlids;
        PD_DocumentRDFHandle inrdf = pDocRange->m_pDoc->getDocumentRDF();
        inrdf->addRelevantIDsForRange( xmlids, pDocRange );

        if( !xmlids.empty() )
        {
            UT_DEBUGMSG(("MIQ: ODF export creating restricted RDF model xmlids.sz:%ld \n",(long)xmlids.size()));
            PD_RDFModelHandle subm = inrdf->createRestrictedModelForXMLIDs( xmlids );
            PD_DocumentRDFMutationHandle m = outrdf->createMutation();
            m->add( subm );
            m->commit();
            subm->dumpModel("copied rdf triples subm");
            outrdf->dumpModel("copied rdf triples result");
        }
        
        // PD_DocumentRDFMutationHandle m = outrdf->createMutation();
        // m->add( PD_URI("http://www.example.com/foo"),
        //         PD_URI("http://www.example.com/bar"),
        //         PD_Literal("copyToBuffer path") );
        // m->commit();
    }
    outDoc->finishRawCreation();
    //
    // OK now we have a complete and valid document containing our selected 
    // content. We export this to an in memory GSF buffer
    //
    IE_Exp * pNewExp = NULL; 
    char *szTempFileName = NULL;
    GError *err = NULL;
    g_file_open_tmp ("XXXXXX", &szTempFileName, &err);
    GsfOutput * outBuf =  gsf_output_stdio_new (szTempFileName,&err);
    IEFileType ftODT = IE_Exp::fileTypeForMimetype("application/vnd.oasis.opendocument.text");
    UT_Error aerr = IE_Exp::constructExporter(outDoc,outBuf,
					     ftODT,&pNewExp);
    if(pNewExp == NULL)
    {
         return aerr;
    }
    aerr = pNewExp->writeFile(szTempFileName);
    if(aerr != UT_OK)
    {
	delete pNewExp;
	delete pRangeListener;
	UNREFP( outDoc);
	g_remove(szTempFileName);
	g_free (szTempFileName);
	return aerr;
    }
    //
    // File is closed at the end of the export. Open it again.
    //

    GsfInput *  fData = gsf_input_stdio_new(szTempFileName,&err);
    UT_DebugOnly<UT_sint32> siz = gsf_input_size(fData);
    const UT_Byte * pData = gsf_input_read(fData,gsf_input_size(fData),NULL);
    UT_DEBUGMSG(("Writing %d bytes to clipboard \n", (UT_sint32)siz));
    bufODT->append( pData, gsf_input_size(fData));
    
    delete pNewExp;
    delete pRangeListener;
    UNREFP( outDoc);
    g_remove(szTempFileName);
    g_free (szTempFileName);
    return aerr;
}
UT_Error IE_Imp_OpenDocument::_handleRDFStreams ()
{
#ifndef WITH_REDLAND
    return UT_OK;
#else
    UT_Error error = UT_OK;
    
    UT_DEBUGMSG(("IE_Imp_OpenDocument::_handleRDFStreams()\n"));

    // // DEBUG.
    // {
    //     PD_DocumentRDFHandle rdf = getDoc()->getDocumentRDF();
    //     PD_DocumentRDFMutationHandle m = rdf->createMutation();
    //     m->add( PD_URI("http://www.example.com/foo#bar" ),
    //             PD_URI("http://www.example.com/foo#bar" ),
    //             PD_Object("http://www.example.com/foo#bar" ) );
    //     m->commit();
    //     rdf->dumpModel("added foo");
    // }
    

    
    RDFArguments args;
    librdf_model* model = args.model;

    // check if we can load a manifest.rdf file
    GsfInput* pRdfManifest = gsf_infile_child_by_name(m_pGsfInfile, "manifest.rdf");
    if (pRdfManifest)
    {
        UT_DEBUGMSG(("IE_Imp_OpenDocument::_handleRDFStreams() have manifest.rdf\n"));
        error = _loadRDFFromFile( pRdfManifest, "manifest.rdf", &args );
        g_object_unref (G_OBJECT (pRdfManifest));
        if (error != UT_OK)
            return error;
    }

    // find other RDF/XML files referenced in the manifest
    const char* query_string = ""
        "prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n"
        "prefix odf: <http://docs.oasis-open.org/opendocument/meta/package/odf#> \n"
        "prefix odfcommon: <http://docs.oasis-open.org/opendocument/meta/package/common#> \n"
        "select ?subj ?fileName \n"
        " where { \n"
        "  ?subj rdf:type odf:MetaDataFile . \n"
        "  ?subj odfcommon:path ?fileName  \n"
        " } \n";

    librdf_uri*   base_uri = 0;
    librdf_query* query = librdf_new_query( args.world, "sparql", 0,
                                            (unsigned char*)query_string,
                                            base_uri );
    librdf_query_results* results = librdf_query_execute( query, model );

    if( !results )
    {
        // Query failed is a failure to execute the SPARQL,
        // in which case there might be results but we couldn't find them
        UT_DEBUGMSG(("IE_Imp_OpenDocument::_handleRDFStreams() SPARQL query to find auxillary RDF/XML files failed! q:%p\n", query ));
        error = UT_ERROR;
    }
    else
    {
        UT_DEBUGMSG(("IE_Imp_OpenDocument::_handleRDFStreams() aux RDF/XML file count:%d\n",
                     librdf_query_results_get_count( results )));

        // parse auxillary RDF/XML files too
        for( ; !librdf_query_results_finished( results ) ;
             librdf_query_results_next( results ))
        {
            librdf_node* fnNode = librdf_query_results_get_binding_value_by_name
                ( results, "fileName" );
            UT_DEBUGMSG(("_handleRDFStreams() fnNode:%p\n", fnNode ));
            std::string fn = toString(fnNode);
        
            UT_DEBUGMSG(("_handleRDFStreams() loading auxilary RDF/XML file from:%s\n",
                         fn.c_str()));
            GsfInput* pAuxRDF = gsf_infile_child_by_name(m_pGsfInfile, fn.c_str());
            if (pAuxRDF) {
                error = _loadRDFFromFile( pAuxRDF, fn.c_str(), &args );
                g_object_unref (G_OBJECT (pAuxRDF));
                if( error != UT_OK )
                    break;
            } else {
                UT_ASSERT_HARMLESS(UT_SHOULD_NOT_HAPPEN);
                return UT_ERROR;
            }
        }
        librdf_free_query_results( results );
    }
    librdf_free_query( query );

    UT_DEBUGMSG(("_handleRDFStreams() error:%d model.sz:%d\n",
                 error, librdf_model_size( model )));
    if( error != UT_OK )
    {
        return error;
    }
    
    // convert the redland model into native AbiWord RDF triples
    {
        PD_DocumentRDFHandle rdf = getDoc()->getDocumentRDF();
        PD_DocumentRDFMutationHandle m = rdf->createMutation();
        librdf_statement* statement = librdf_new_statement( args.world );
        librdf_stream* stream = librdf_model_find_statements( model, statement );

		while (!librdf_stream_end(stream))
        {
            librdf_statement* current = librdf_stream_get_object( stream );

            int objectType = PD_Object::OBJECT_TYPE_URI;
            
            std::string xsdType = "";
            if( librdf_node_is_blank( librdf_statement_get_object( current )))
            {
                objectType = PD_Object::OBJECT_TYPE_BNODE;
            }
            if( librdf_node_is_literal( librdf_statement_get_object( current )))
            {
                objectType = PD_Object::OBJECT_TYPE_LITERAL;
                if( librdf_uri* u = librdf_node_get_literal_value_datatype_uri(
                        librdf_statement_get_object( current )))
                {
                    xsdType = toString(u);
                }
            }

            if( DEBUG_RDF_IO )
            {
                UT_DEBUGMSG(("_handleRDFStreams() adding s:%s p:%s o:%s rotv:%d otv:%d ots:%s\n",
                             toString( librdf_statement_get_subject( current )).c_str(),
                             toString( librdf_statement_get_predicate( current )).c_str(),
                             toString( librdf_statement_get_object( current )).c_str(),
                             librdf_node_get_type(librdf_statement_get_object( current )),
                             objectType,
                             xsdType.c_str()
                                ));
            }
            
            m->add( PD_URI( toString( librdf_statement_get_subject( current ))),
                    PD_URI( toString( librdf_statement_get_predicate( current ))),
                    PD_Object( toString( librdf_statement_get_object( current )), objectType, xsdType ));

            // m->add( PD_URI( toString( librdf_statement_get_subject( current ))),
            //         PD_URI( toString( librdf_statement_get_predicate( current ))),
            //         PD_Object( toString( librdf_statement_get_object( current )),
            //                    objectType,
            //                    xsdType ));

            librdf_stream_next(stream);
        }
        
        librdf_free_stream( stream );
        librdf_free_statement( statement );
        // m->add( PD_URI("http://www.example.com/foo#bar" ),
        //         PD_URI("http://www.example.com/foo#bar" ),
        //         PD_Object("http://www.example.com/foo#bar" ) );
        m->commit();
    }

    if( DEBUG_RDF_IO )
    {
        getDoc()->getDocumentRDF()->dumpModel("Loaded RDF from ODF file");
    }
    return error;
#endif
}