package ID3FS::AudioFile::Flac;

use strict;
use warnings;
use Audio::FLAC::Header;

sub new
{
    my $proto=shift;
    my $class=ref($proto) || $proto;
    my $self={};
    bless($self,$class);

    $self->{path}=shift;
    my $flac=Audio::FLAC::Header->new($self->{path});
    $self->{tags}=$flac->tags();
    return $self;
}

sub get
{
    my ($self, $tag, $complain)=@_;
    for my $key (keys %{$self->{tags}})
    {
	if($key =~ /$tag/i &&
	   defined($self->{tags}->{$key})  &&
	   length($self->{tags}->{$key})   &&
	   $self->{tags}->{$key} =~ /\S+/)
	{
	    my $val=$self->{tags}->{$key};
	    $val =~ s/\//-/g; # drop slashes
	    return $val;
	}
    }
    warn("$self->{path}: no $tag defined in FLAC comments\n") if($complain);
    return undef;
}

sub artist    { shift->get("ARTIST", 1); }
sub album     { shift->get("ALBUM", 1);  }
sub audiotype { return "flac";           }
sub haspic    { return undef;            } # FIXME
sub v1genre   { return undef;            } # ID3 only

# We don't care if year is not set
sub year
{
    my ($self)=@_;
    my $date=shift->get("DATE", 0);
    return undef unless($date);
    if($date =~/(\d\d\d\d)/)
    {
	$date=$1;
    }
    return $date;
}

sub tags
{
    my $self=shift;
    my @tags=();
    my $tags={};
    for my $key (keys %{$self->{tags}})
    {
	print "CONSIDERING: $key\n";
	if($key =~ /genre/i &&
	   defined($self->{tags}->{$key})  &&
	   length($self->{tags}->{$key})   &&
	   $self->{tags}->{$key} =~ /\S+/)
	{
	    print "KEY: $key, val: ", $self->{tags}->{$key}, "\n";
	    push(@tags, $self->{tags}->{$key});
	}
    }
    # combine then split on commas
    # so multiple comma-delimited tags will work
    @tags=split(/\s*,\s*/, join(', ', @tags));
    for my $tag (@tags)
    {
	if($tag=~/([^\/]+)\/(.*)/)
	{
	    my $tagname=$1;
	    my $tagval=$2;
	    $tagval=~s/\//-/g;
	    $tags->{$tagname}=$tagval;
	}
	else
	{
	    $tags->{$tag}=undef;
	}
    }
    return $tags;
}

1;

