package ID3FS::AudioFile;

use strict;
use warnings;
use ID3FS::AudioFile::Mp3;
use ID3FS::AudioFile::Ogg;
use ID3FS::AudioFile::Flac;

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

    my $path=shift;
    my $ext=($path=~/.*\.(.*)/)[0];
    return undef unless($ext);
    my $me=shift;
    $ext=lc($ext);
    if($ext eq "mp3")
    {
	$self->{audiofile}=ID3FS::AudioFile::Mp3->new($path);
    }
    elsif($ext eq "ogg")
    {
	$self->{audiofile}=ID3FS::AudioFile::Ogg->new($path);
    }
    elsif($ext eq "flac")
    {
	$self->{audiofile}=ID3FS::AudioFile::Flac->new($path);
    }
    else
    {
	print("$me: $path: Unknown extension: $ext\n");
	return undef;
    }
    return $self;
}

sub artist
{
    my $self=shift;
    return $self->sanitise($self->stripslashes($self->{audiofile}->artist()));
}

sub album
{
    my $self=shift;
    return $self->sanitise($self->stripslashes($self->{audiofile}->album()));
}

sub audiotype
{
    my $self=shift;
    return $self->sanitise($self->stripslashes($self->{audiofile}->audiotype()));
}

sub haspic
{
    return undef; # FIXME
#    my $self=shift;
#    return $self->{audiofile}->haspic();
}

sub v1genre
{
    my $self=shift;
    return $self->sanitise($self->stripslashes($self->{audiofile}->v1genre()));
}

sub year
{
    my $self=shift;
    my $year=$self->sanitise($self->stripslashes($self->{audiofile}->year()));
    if(defined($year) && $year =~/(\d{4})/)
    {
	$year=$1;
    }
    return $year;
}

sub tags
{
    my $self=shift;
    my @tags=$self->{audiofile}->tags();
    return({}) unless(@tags);
    my $tags={};
    if(@tags)
    {
	@tags = grep { defined($_); } @tags;
	# combine then split on commas
	# so multiple comma-delimited tags will work
	@tags=split(/\s*,\s*/, join(', ', @tags));
	for my $tag (@tags)
	{
	    next unless(length($tag));
	    next unless($tag =~ /\S+/);
	    $tag=$self->sanitise($tag);

	    if($tag=~/([^\/]+)\/(.*)/)
	    {
		my $tagname = $1;
		my $tagval  = $self->stripslashes($2);
		$tags->{$tagname}=$tagval;
	    }
	    else
	    {
		$tags->{$tag}=undef;
	    }
	}
    }
    return $tags;
}

sub sanitise
{
    my ($self, $text)=@_;
    $text =~ s/[^[:print:]]//g if(defined($text));
    return $text;
}

sub stripslashes
{
    my ($self, $text)=@_;
    $text =~ s/\//-/g if(defined($text));
    return $text;
}

1;
