#!/usr/bin/perl
# Copyright 1999-2012. Parallels IP Holdings GmbH. All Rights Reserved.

package Storage::FileNameCreator;


use strict;
#use Text::Iconv;


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


sub _init{
  my( $self ) = @_;
  if( eval( "require use Text::Iconv" ) ){
	  $self->{iconv} = Text::Iconv->new("UTF-8", "ASCII//TRANSLIT" );
  }
  my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) =  localtime(time);
  $year -= 100;
  $year = 0 if $year<0;
  $self->{dateprefix} = sprintf( "%0.2d%0.2d%0.2d%0.2d%0.2d",$year,$mon+1,$mday,$hour,$min);
}


sub getFileName{
  my ($self, $normalizedPath, $normalizedbackupfileName, $normalizedObjectId, $fileName ) = @_;
  my $ret = '';
  $ret .= "$normalizedPath/" if $normalizedPath;
  $ret .= "$normalizedbackupfileName\_" if $normalizedbackupfileName;
  $ret .= "$normalizedObjectId\_" if $normalizedObjectId;
  $ret .= $fileName . '_' if $fileName;
  $ret .= $self->{dateprefix};
  return $ret;
}

sub normalize_long_string{
  my ($self, $str, $id) = @_;
  return $self->normalize_string( $str, $id, 47 );
}

sub normalize_short_string{
  my ($self, $str, $id) = @_;
  return $self->normalize_string( $str, $id, 25 );
}


sub replace_danger{
 my ($self, $str) = @_;
 #danger:  " ", ":", ">",   "<",   "|", "&",     "!"
 #replace: "_", "-", "-gt-","-lt-","_", "-and-", "_"

 if ( $str =~ /[\ :><\|&!]/s ) {
    $str =~ s/\ /_/sg;
    $str =~ s/:/-/sg;
    $str =~ s/>/-gt-/sg;
    $str =~ s/</-lt-/sg;
    $str =~ s/\|/_/sg;
    $str =~ s/&/-and-/sg;
    $str =~ s/!/_/sg;
  }
  return $str;
}

sub normalize_string{
 my ($self, $str, $id, $max_length) = @_;

 my $res_orig = $str;
 $res_orig = $self->{iconv}->convert( $str ) if exists $self->{iconv};
 my $res = $res_orig;
 $res = $self->replace_danger( $res_orig );

 if( length($res) > $max_length ){
      $res = substr( $res, 0, $max_length - length($id) - 1 ) . "_" . $id;
 }
 elsif($res_orig ne $res){
    my $newLen = length($res);
    $newLen = $max_length - length($id) - 1 if $newLen + length($id) + 1 > $max_length;
    $res = substr( $res, 0, $newLen ) . "_" . $id;
 }
 return $res;
}


sub normalize_id_string{
 my ($self, $str, $id, $max_length) = @_;

 my $res_orig = $str;
 $res_orig = $self->{iconv}->convert( $str ) if exists $self->{iconv};
 my $res = $self->replace_danger( $res_orig );

 if( $max_length and length($res) > $max_length ){
     $res = substr( $res, 0, $max_length );
 }
 return $res;
}






1;