#------------------------------------------------------------
# Copyright (C) 2008 RoyaltyShare, Inc.   All Rights Reserved
#------------------------------------------------------------

#------------------------------------------------------------
# Distribution utility class containg random exported functions
#------------------------------------------------------------
package Distribution::Util;

use File::Path;
use XML::Twig;

use base Exporter;

use lib '/app/tools/rps/lib';

@EXPORT    = qw( mkdir_local );
@EXPORT_OK = qw( );

#------------------------------------------------------------
# bool mkdir_local( $path )
#
# Create a path if it doesn't already exist
#
# Parameters:
#   $path - path name of the directory you want to create
#
# Return:
#   int - 1 if the directory was created properly
#         2 if the directory already exists
#         0 if we couldn't create the directory
#------------------------------------------------------------
sub mkdir_local {
    my $path = shift || croak("path requred");

    die "requred" unless ($path);

    if ( -f $path ) {
        Common::Log::Print("ERROR: $path is a file, can not overwrite");
        return 0;
    }

    if ( -d $path ) {
        Common::Log::Debug("$path already exists, not creating");
        return 2;
    }

    my $current_pwd = '';

    Common::Log::Debug("Building path: $path");

    my @dirs = split( /[\\\/]/, $path );
    my $tmpdir = shift @dirs;

    for my $dir (@dirs) {
        $tmpdir .= "/$dir";
        mkdir $tmpdir;
    }

    return 1;
}

sub seconds_to_iso8601 {
    my $seconds = shift;
    my $minutes = int( $seconds / 60 );
    $seconds = $seconds - ( $minutes * 60 );
    return "PT${minutes}M${seconds}S";
}

sub xml_pp {
    my $xml = shift || die;

    my $twig = new XML::Twig(
        pretty_print   => 'indented',
        keep_spaces_in => 0,
        empty_tags     => 'html',
    );

    #Common::Log::Print( $xml );

    eval { $twig->parse($xml) };
    if ($@) {
        print STDERR "$xml";
        die $@;
    }

    return $twig->sprint( PrettyPrint => 'indented', EmptyTags => 'html' );
}

1;
