package File::Util;

use strict;
use warnings;
use lib '/app/tools/common/lib';
use Common::Consts;
use Common::Client;

#  in: a file handle
# out: the service id associated with this file
sub GetServiceID {
    my $file_path = shift;

    return 0;

    # this lets us reset the file handle
}

sub SaveTmpUpload {
    my %args        = @_;
    my $file_name   = $args{name} or return undef;
    my $fh          = $args{handle} or return undef;
    my $client_id   = $args{client_id} or return undef;
    my $client_name = GetClientNameClean($client_id);

    my $path          = "/app/shared/sale_import/$client_name/tmp";
    my $tmp_file_path = "$path/$file_name";
    open( FILE, $tmp_file_path ) or return undef;
    while (<$fh>) {
        print FILE $_;
    }
    close(FILE);

    return $tmp_file_path;
}

sub SaveFileUpload {
    my %args        = @_;
    my $client_id   = $args{client_id} or return undef;
    my $service_id  = $args{service_id} or return undef;
    my $period_id   = $args{period_id} or return undef;
    my $source_file = $args{src} or return undef;
    return undef if ( !-f $source_file );

    my $client_name  = GetClientNameClean($client_id);
    my $service_name = GetServiceNameClean($service_id);
    my $timestamp    = GetTimeStamp();
    my $ext;
    ($ext) = $source_file =~ /\.(\w+)$/;

    print STDERR "client: $client_name ($client_id)\n";
    print STDERR "service: $service_name ($service_id)\n";
    print STDERR "period: $period_id\n";
    print STDERR "src file: '$source_file'\n";
    print STDERR "extension: $ext\n";

    # setup the dirs
    my $base_dir        = "/app/data";
    my $client_dir      = "$base_dir/$client_name";
    my $dest_dir        = "$client_dir/$period_id";
    my $new_file_name   = $service_name . "_" . $timestamp . "." . $ext;
    my $final_file_path = "$dest_dir/$new_file_name";

    print STDERR "cp $source_file $final_file_path\n";

    `mkdir $client_dir` if ( !-d $client_dir );
    `mkdir $dest_dir`   if ( !-d $dest_dir );

    # do it. do it now.
    `cp $source_file $final_file_path`;
    if ( -f $final_file_path ) {
        `rm $source_file`;
    } else {
        return undef;
    }

    return $final_file_path;
}

sub GetServiceNameClean {
    my $service_id = shift;

    # eventually, do this
    # my $service = new Service($service_id);
    # return $service->ServiceNameClean;

    # but for now do this
    return $Common::Consts::SERVICE_NAME_CLEAN{$service_id};
}

sub GetClientNameClean {
    my $client_id = shift;

    # eventually, do this
    my $client = Common::Client->new( clientID => $client_id );
    return $client->ClientNameClean;

    # but for now do this
    #	return $Common::Consts::CLIENT_NAME_CLEAN{$client_id};
}

sub GetTimeStamp {
    my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) = localtime(time);
    return sprintf "%4d%02d%02d%02d%02d%02d", $year + 1900, $mon + 1, $mday, $hour, $min, $sec;
}

###
1;    # Play nicely.
###
