package Common::File::Tied::LineParser::CSV;
use strict;

# !!! This library doesn't work as well as we'd like, apparently.
#
use Text::CSV_XS;

use lib '/app/tools/common/lib';
use Common::Assert;

use base 'Common::File::Tied::LineParser';

sub _init {
    my ( $self, %args ) = @_;

    # We see a lot of so-called 'CSV' files that do a variety of weird stuff.
    # So we'll create a set of CSV parser objects with different options.
    #
    # !!! I may set up a pseudo-'heap', so that the last CSV parser that worked
    #     will be tried first next time.

    $self->{_csv_1} = Text::CSV_XS->new( { binary => 1 } );

    return $self->SUPER::_init(%args);
}

sub parseString {
    my ( $self, $string ) = @_;

    # JPK - In the original _read_text_file method in Sale::File, we do all sorts of crazy crap
    # to deal with the non-standard encodings we see.
    # We're going to have to deal with that again, I'm certain.
    # I'm hoping we can be a little less ragged in our implementation.
    #
    # I don't even think we can assume, once we've seen something unusual, that the rest of
    # the file will be that way.   So, alas, it's probably best to be prepared to apply all
    # parsing strategies to each line...
    #
    my @bits;
    if ( $self->{_csv_1}->parse($string) ) {
        @bits = $self->{_csv_1}->fields();
    } else {
        die "Common::File::Tied::LineParser::CSV ERROR: " . $self->{_csv_1}->error_diag();
    }

    return \@bits;
}

1;
