# This document processor saves a document in the 
# archives directory of a collection


package docsave;

use arcinfo;
use docproc;
use util;


sub BEGIN {
    @ISA = ('docproc');
}

sub new {
    my ($class, $collection, $archive_info) = @_;
    my $self = new docproc ();

    $self->{'collection'} = $collection;
    $self->{'archive_info'} = $archive_info;

    return bless $self, $class;
}

sub process {
    my $self = shift (@_);
    my ($doc_obj) = @_;

    my $archive_dir = "$ENV{'GSDLHOME'}/collect/$self->{'collection'}/archives";
    my $OID = $doc_obj->get_OID();
    $OID = "NULL" unless defined $OID;

    # get the document's directory by inserting a / every 1-8 characters
    # and removing the last /
    my $doc_dir = $OID;
    $doc_dir =~ s/(.{1,8})/$1\//g;
    $doc_dir =~ s/\/$//;
    $doc_dir .= ".dir";
    &util::mk_all_dir ("$archive_dir/$doc_dir");

    # copy all the associated files, add this information as metadata
    # to the document
    my @assoc_files = ();
    foreach $assoc_file (@{$doc_obj->get_assoc_files()}) {
	if (-e $assoc_file->[0]) {
	    &util::cp ($assoc_file->[0], "$archive_dir/$doc_dir/$assoc_file->[1]");
	    $doc_obj->add_metadata ($doc_obj->get_top_section(), 
				    "gsdlassocfile", 
				    "$assoc_file->[1]:$assoc_file->[2]");
	} else {
	    print STDERR "docsave::process couldn't copy the associated file " .
		"$assoc_file->[0] to $archive_dir/$doc_dir/$assoc_file->[1]\n"
	}
    }

    # save this document
    if (!open (OUTDOC, ">$archive_dir/$doc_dir/doc.gml")) {
	print STDERR "docsave::process could not write to file " . 
	    "$archive_dir/$doc_dir/doc.gml\n";
	return;
    }
    $doc_obj->output_section('docsave::OUTDOC', $doc_obj->get_top_section());
    close OUTDOC;

    # store reference in the archive_info
    $self->{'archive_info'}->add_info($OID, 
				      "$doc_dir/doc.gml");
    
}


1;
