use utf8;
package Document::OOXML::Document;
use Moose;

# ABSTRACT: Base class for the different OOXML document types


has filename => (
    is  => 'ro',
    isa => 'Str',
);

has source => (
    is       => 'ro',
    isa      => 'Archive::Zip',
    required => 1,
);

has is_strict => (
    is       => 'ro',
    isa      => 'Bool',
    required => 1,
);

has document_part => (
    is      => 'rw',
    isa     => 'Document::OOXML::Part',
    writer  => 'set_document_part',
);

has loaded_parts => (
    is      => 'ro',
    isa     => 'HashRef[Document::OOXML::Part]',
    default => sub { {} },
);

has content_types => (
    is       => 'ro',
    isa      => 'Document::OOXML::ContentTypes',
    required => 1,
);


sub save_to_file {
    my $self = shift;
    my $filename = shift;

    my $output = Archive::Zip->new();

    for my $member ( $self->source->members() ) {
        if ($member->fileName eq $self->document_part->part_name) {
            $output->addString(
                $self->document_part->to_string(),
                $self->document_part->part_name,
            );
        } elsif (exists $self->loaded_parts->{$member->fileName}) {
            my $part = $self->loaded_parts->{$member->fileName};
            $output->addString(
                $part->to_string(),
                $part->part_name,
            );
        } else {
            # File not changed by us. Copy verbatim.
            $output->addMember($member);
        }
    }

    $output->writeToFileNamed($filename);

    return;
}

__PACKAGE__->meta->make_immutable();

__END__

=pod

=encoding UTF-8

=head1 NAME

Document::OOXML::Document - Base class for the different OOXML document types

=head1 VERSION

version 0.172600

=head1 SYNOPSIS

    package Document::OOXML::Document::SomeType;
    use Moose;
    extends 'Document::OOXML::Document';

    # implement document-type specifics here

=head1 METHODS

=head2 save_to_file($filename)

Saves the document to the named file.

=head1 SEE ALSO

=over

=item * L<Document::OOXML>

=back

=head1 AUTHOR

Martijn van de Streek <martijn@vandestreek.net>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2017 by Martijn van de Streek.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut
