package ID3FS::File::Mp3;

use strict;
use warnings;
use MP3::Tag;

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

    $self->{path}=shift;
    $self->{mp3}=MP3::Tag->new($self->{path});
    $self->get_tags();
    $self->{v1}=undef;
    $self->{v1}=$self->{mp3}->{ID3v1} if(exists($self->{mp3}->{ID3v1}));
    $self->{v2}=undef;
    $self->{v2}=$self->{mp3}->{ID3v2} if(exists($self->{mp3}->{ID3v2}));

    # FIXME
    $self->{tags}={};

    return $self;
}

sub choose
{
    my ($self, $func, $verbose)=@_;
    my $thing=undef;
    if(defined($self->{v2}))
    {
	$thing=$self->{v2}->$func();
    }
    if(defined($self->{v1}) && (!defined($thing) || !length($thing)))
    {
	$thing=$self->{v1}->$func();
    }
    if(!defined($thing) || !length($thing))
    {
	warn("$self->{path}: no $func defined in ID3 tags\n") if($verbose);
	return undef;
    }
    return $thing;
}

sub artist    { shift->choose("artist", 1); }
sub album     { shift->choose("album", 1);  }
# We don't care if year is not set
sub year      { shift->choose("year", 0);   }
sub audiotype { return "mp3";               }
sub haspic    { return undef;               } # FIXME
sub v1genre
{
    my($self)=@_;
    if(defined($self->{v1}))
    {
	return $self->{v1}->genre();
    }
}

sub tags
{
    my $self=shift;
    return $self->{tags};
}

sub get_tags
{
    my ($self)=@_;
    # MP3::Tag->get_tags shows cryptic debug info via print when it finds
    # an unhandled id3v2 version, in addition to the warning, so use
    # select to send prints to /dev/null
    my $oldout=undef;
    if(open(NULL,">/dev/null"))
    {
	$oldout=select(NULL);
    }
    eval { $self->{mp3}->get_tags; };
    warn("$self->{path}: $@\n") if($@);
    if(defined($oldout))
    {
	select($oldout);
	close(NULL);
    }
}

1;

