package Common::File::Tied::LineParser::Factory;
use strict;
use lib '/app/tools/common/lib';

use Common::File::Tied::LineParser::TabDelimited;
use Common::File::Tied::LineParser::CSV;

sub CreateParser {
    my ( $class, $file ) = @_;

    # !!! Eventually this will do something clever.
    # !!! But for now, we'll do something stupid. :)
    #
    my $delimeter = GetDelimiter($file);

    if ( "\t" eq $delimeter ) {
        return Common::File::Tied::LineParser::TabDelimited->new();
    }

    if ( ',' eq $delimeter ) {
        return Common::File::Tied::LineParser::CSV->new();
    }
}

# This also lives in Common::Util.
# But this version knows how to use the Common::File interface.
#
sub GetDelimiter {
    my $file = shift;
    my $delimiter;
    my $slurp;

    # Read the first 1000 characters (up to, anyway) from the file.
    # We'll reset the file position once we're done to what it was originally.
    #
    my $fh      = $file->filehandle();
    my $savePos = tell($fh);
    seek( $fh, 0, 0 );

    my $charCount;
    my $line;
    while ( $line = $file->readLine() ) {
        $charCount += length($line);
        $slurp .= $line;
        last if $charCount > 1000;
    }

    seek( $fh, $savePos, 0 );

    my $cntComma = () = $slurp =~ /\,/g;
    my $cntTab   = () = $slurp =~ /\t/g;
    my $cntPipe  = () = $slurp =~ /\|/g;
    my $cntSemi  = () = $slurp =~ /\;/g;

    if ( $cntPipe > $cntTab ) {
        if ( $cntPipe > $cntComma ) {
            $delimiter = '\|';
        }
    } elsif ( $cntTab > $cntComma ) {
        $delimiter = "\t";
    } elsif ( $cntSemi > $cntComma ) {
        $delimiter = ";";
    }

    if ( !$delimiter && $cntComma ) {
        $delimiter = ",";
    }

    return $delimiter;
}

1;
