# Copyright 1999-2012. Parallels IP Holdings GmbH. All Rights Reserved.
package ContentTransport::Archive;

use strict;

use Logging;
use Storage::ContentNameCreator;
use ContentTransport::ContentTransport;

use vars qw|@ISA|;

@ISA = qw|ContentTransport::ContentTransport|;

sub new {
  my $self = {};
  bless( $self, shift );
  $self->_init(@_);
  return $self;
}

sub _init{
  my( $self, $options, $storagepolicy ) = @_;
  $self->SUPER::_init( $options );
  $self->{storage} = $storagepolicy;
}

sub getContentTransportDescription {
  my $self = shift;
  return;
}

sub addContent {
  my $self = shift;
  my $cid_type = shift;
  my $proposedId = shift; # filename is used as proposed id for archive
  my %options = @_;

  return if exists $self->{skip_content};

  return unless (-d $options{'directory'});

  my $contentId = $self->{storage}->addTar($proposedId, %options);
  return unless defined $contentId;

  return $self->_makeCidNode($contentId, $cid_type);
}

sub addDbContent {
  my $self = shift;
  my $proposedId = shift; # filename is used as proposed id for archive
  my %params = @_;

  my $contentId = $self->{storage}->addDb($proposedId, %params);
  return unless defined $contentId;

  return $self->_makeCidNode($contentId, 'sqldump')
}

sub _makeCidNode{
  my ($self, $contentId, $cid_type ) = @_;
  my $cid = XmlNode->new( 'cid' );
  $cid->setAttribute( 'type', $cid_type );
  $cid->setAttribute( 'unpacksize', $self->{storage}->getFilesUnpackSizeFromId($contentId) );
  $cid->setAttribute( 'path', $self->{storage}->getFilePathFromId( $contentId ) );

  my $files = $self->{storage}->getFilesFromId( $contentId );
  foreach my $filedata( @{$files} ){
    $cid->addChild( XmlNode->new( 'content-file', 'content' => $filedata->[0], 'attributes' => {'size' => $filedata->[1] } ) );
  }
  return $cid;
}

1;
