# Copyright 1999-2015. 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 $self->_skipContent(%options);

  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, %options) = @_;
  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] } ) );
  }

  if (defined($options{'include'})) {
    my @includes = @{$options{'include'}};
    foreach my $inc (@includes) {
      $cid->addChild(XmlNode->new('include-item', 'content' => $inc));
    }
  }

  if (defined($options{'exclude'})) {
    my @excludes = @{$options{'exclude'}};
    foreach my $exc (@excludes) {
      $cid->addChild(XmlNode->new('exclude-item', 'content' => $exc));
    }
  }

  return $cid;
}

1;
