# UBMA: export plugin for lists in branded office document
package EPrints::Plugin::Export::Office;

use File::Copy;
use OpenOffice::OODoc;
use EPrints::Plugin::Export;

@ISA = ( "EPrints::Plugin::Export" );

use strict;

sub new
{
    my( $class, %opts ) = @_;

    my( $self ) = $class->SUPER::new( %opts );

    $self->{name} = "Office Document";
    $self->{accept} = [ 'list/eprint' ];
    $self->{visible} = "all";
    $self->{suffix} = ".odt";
    $self->{mimetype} = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";

    return $self;
}

sub output_list
{
    my( $self, %opts ) = @_;

    ## TODO: use temp file in production
    #my $output = File::Temp->new(SUFFIX => '.odt');
    my $output = "/data/madoc/test.odt"; # persistent file for testing purposes
    copy("/data/madoc/template.odt", "$output");
    EPrints::Utils::chown_for_eprints( "$output" );

    open(my $FH, "+<", $output);
    ## alternative file handling from ooffice documentation:
    #my $FH = new IO::File "< $output";
    #binmode $FH;

    ## Create container from FH
    my $container = odfContainer(
        $FH,
        work_dir => "/data/madoc/"
    );
    ## Alternative approach to copying the file like above:
    ## create new container via template. should automatically be saved in work_dir
    #my $container = odfContainer(
    #    undef,
    #    create => "text",
    #    template_path => "/data/madoc/",
    #    work_dir => "/data/madoc/"
    #);
    die("Unable to open/create container: $!") unless defined $container;

    my $content = odfDocument(
        container => $container,
        part => 'content'
    );
    $content->selectElementsByContent("Title", "Citation List");
    foreach my $eprint ($opts{list}->get_records) {
        my $newparagraph = $content->appendParagraph(
            # TODO: render nice citation here
            text => $eprint->id()
            #text            => $eprint->render_citation
            #text            => EPrints::Utils::tree_to_utf8($eprint->render_citation,undef,undef,undef,1)
        );
    }
    $container->save();

    ## return --> web export result
    return $FH; # --> unstyled document containing "GLOB(0xfoo)" (this one I expected to work, the rest is just for the sake of completeness)
    #return $output; --> unstyled document containing "/data/madoc/test.odt"
    #return $container; --> unstyled document containing "OpenOffice::OODoc::File=HASH(0xbar)"
    #return $content; --> unstyled document containing "OpenOffice::OODoc::Document=HASH(0xbaz)"
    #return undef; # --> unstyled, empty document
}

1;

