package ID3FS::Path;

use strict;
use warnings;
use ID3FS::Path::Node;

our ($STATE_INVALID, $STATE_ROOT, $STATE_TAG, $STATE_TAGVAL,
     $STATE_BOOLEAN, $STATE_ALBUMS, $STATE_TRACKLIST,
     $STATE_FILE, $STATE_ALL)=(0..8);

our %priorities=( "OR" => 0, "AND" => 1, "NOT" => 2 );

our $PATH_ALLTRACKS= "TRACKS";
our $PATH_NOARTIST = "NOARTIST";
our $PATH_NOALBUM  = "NOALBUM";

our $ENABLE_FILTER = 1;

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

    $self->{elements}=[];
    $self->{db}=shift;
    $self->{path}=shift;
    $self->{verbose}=shift;
    $self->{maxtagdepth}=shift;
    $self->{curtagdepth}=0;
    $self->{path} =~ s/\/\//\//g; # drop doubled slashes

    $self->parse();
#    print "STATE: ", $self->state(), "\n";
    return $self;
}

sub isdir
{
    my($self)=@_;
    if(($self->state() == $STATE_FILE) ||
       ($self->state() == $STATE_INVALID))
    {
	return 0;
    }
    return 1;
}

sub isfile
{
    my($self)=@_;
    return($self->state() == $STATE_FILE);
}

sub isvalid
{
    my($self)=@_;
    return($self->state() != $STATE_INVALID);
}

sub dest
{
    my($self, $mountpoint)=@_;
    if($self->state() == $STATE_FILE)
    {
	return $self->filename($mountpoint);
    }
    return "ERROR"; #should never happen?
}

sub dirents
{
    my($self)=@_;
    my @dents=();
    my @fents=();
    my $state=$self->state();
#    print "DIRENTS: STATE: $state\n";
#    print "DIRENTS: FILE: $self->{path}\n";
    if($state==$STATE_ALL)
    {
	@dents=($PATH_ALLTRACKS, $PATH_NOARTIST, $self->artists());
    }
    elsif($state==$STATE_TAG || $state==$STATE_TAGVAL)
    {
	if($state==$STATE_TAG && $self->at("tag") &&
	   $self->{db}->tag_has_values($self->tail()->id()))
	{
	    @dents=$self->tags();
	}
	else
	{
	    if($self->{maxtagdepth} && ($self->{curtagdepth} < $self->{maxtagdepth}))
	    {
		@dents=qw(AND OR);
	    }
	    push(@dents, ($ENABLE_FILTER ?
			  $self->filter($PATH_ALLTRACKS, $PATH_NOARTIST) :
			  ($PATH_ALLTRACKS, $PATH_NOARTIST)));
	    push(@dents, $self->artists());
	}
    }
    elsif($state==$STATE_BOOLEAN)
    {
	my $parent=$self->tail();
	unless($self->is("boolean", $parent) &&
	       $parent->{name} eq "NOT")
	{
	    @dents=("NOT");
	}
	push(@dents,$self->tags());
    }
    elsif($state==$STATE_ROOT)
    {
	@dents=(qw(ALL NOT), $self->tags());
    }
    elsif($state==$STATE_ALBUMS)
    {
	@dents=($self->filter($PATH_ALLTRACKS, $PATH_NOALBUM), $self->albums());
    }
    elsif($state==$STATE_TRACKLIST)
    {
	@fents=$self->tracks();
    }
    else
    {
	print "DIRENTS: UNHANDLED STATE: $state\n";
    }
    return(\@dents, \@fents);
}

sub parse
{
    my($self)=@_;
    @{$self->{components}}=split(/\//, $self->{path});
    shift @{$self->{components}}; # drop empty field before leading /
#    print "PATH: $self->{path}\n";
    $self->state($STATE_ROOT);
    return if($self->{path} eq "/");
    my @parts=@{$self->{components}};
    my($tag, $tagval);
    $self->{elements}=[];
    $self->{in_all}=0;
    my $root_not=0;
    my $tags_seen=0;
    while(defined(my $name=shift @parts))
    {
#	print "NAME: $name\n";
	my $state=$self->state();
	if($state==$STATE_INVALID)
	{
#	    print "SM: INVALID: $name\n";
	    return;
	}
	elsif($state==$STATE_ROOT)
	{
#	    print "SM: ROOT: $name\n";
	    if($name eq "ALL")
	    {
		$self->{in_all}=1;
		$self->state($STATE_ALL);
	    }
	    elsif($name eq "NOT")
	    {
		$root_not=1;
	        push(@{$self->{elements}}, ID3FS::Path::Node->new($self->{db}, "boolean", $name));
		$self->state($STATE_BOOLEAN);
	    }
	    else
	    {
		$tag=ID3FS::Path::Node->new($self->{db},"tag", $name);
		if($tag)
		{
		    push(@{$self->{elements}}, $tag);
		    $tags_seen++;
		    $self->state($STATE_TAG);
		}
		else
		{
		    $self->state($STATE_INVALID);
		}
	    }
	}
	elsif($state==$STATE_TAG || $state==$STATE_TAGVAL)
	{
	    my $tag=$self->tail();
#	    print "SM: TAG/TAGVAL($state): $name\n";
	    if($state==$STATE_TAG && $self->is("tag", $tag) &&
	       $self->{db}->tag_has_values($tag->id()))
	    {
#		print "Parsing: parent: $tag->id()\n";
		my $tagval=ID3FS::Path::Node->new($self->{db}, "tag", $name, $tag->id());
		if(defined($tagval))
		{
		    $self->state($STATE_TAGVAL);
		    # stay in tag state
		    push(@{$self->{elements}}, $tagval);
		}
		else
		{
		    $self->state($STATE_INVALID);
		}
	    }
	    elsif($name eq $PATH_ALLTRACKS)
	    {
		$self->state($STATE_TRACKLIST);
	    }
	    elsif($name eq $PATH_NOARTIST)
	    {
		$self->state($STATE_TRACKLIST);
	    }
	    elsif($name eq "AND")
	    {
		$self->state($STATE_BOOLEAN);
	        push(@{$self->{elements}}, ID3FS::Path::Node->new($self->{db}, "boolean", $name));
	    }
	    elsif($name eq "OR")
	    {
		$self->state($STATE_BOOLEAN);
	        push(@{$self->{elements}}, ID3FS::Path::Node->new($self->{db}, "boolean", $name));
	    }
	    else
	    {
		my $artist=ID3FS::Path::Node->new($self->{db}, "artist", $name);
		if($artist)
		{
		    push(@{$self->{elements}}, $artist);
		    $self->state($STATE_ALBUMS);
		}
		else
		{
		    $self->state($STATE_INVALID);
		}
	    }
	}
	elsif($state==$STATE_BOOLEAN)
	{
#	    print "SM: BOOLEAN: $name\n";
	    my $parent=$self->tail();
	    my $allownot=1;
	    if($self->is("boolean", $parent) &&
	       $parent->{name} eq "NOT")
	    {
		$allownot=0;
	    }
	    if($allownot && $name eq "NOT")
	    {
		$self->state($STATE_BOOLEAN);
	        push(@{$self->{elements}}, ID3FS::Path::Node->new($self->{db}, "boolean", $name));
	    }
	    else
	    {
		my $tag=ID3FS::Path::Node->new($self->{db}, "tag", $name);
		if($tag)
		{
		    push(@{$self->{elements}}, $tag);
		    $tags_seen++;
		    $self->state($STATE_TAG);
		}
		else
		{
		    $self->state($STATE_INVALID);
		}
	    }
	}
	elsif($state==$STATE_ALBUMS)
	{
#	    print "SM: ALBUM: $name\n";
	    if($name eq $PATH_ALLTRACKS)
	    {
		$self->state($STATE_TRACKLIST);
	    }
	    elsif($name eq $PATH_NOALBUM)
	    {
		$self->state($STATE_TRACKLIST);
	    }
	    else
	    {
		my $album=ID3FS::Path::Node->new($self->{db}, "album", $name);
		if($album)
		{
		    push(@{$self->{elements}}, $album);
		    $self->state($STATE_TRACKLIST);
		}
		else
		{
		    $self->state($STATE_INVALID);
		}
	    }
	}
	elsif($state==$STATE_TRACKLIST)
	{
#	    print "SM: TRACKLIST: $name\n";
	    my $track=ID3FS::Path::Node->new($self->{db}, "file", $name);
	    if($track)
	    {
		push(@{$self->{elements}}, $track);
		$self->state($STATE_FILE);
	    }
	    else
	    {
		$self->state($STATE_INVALID);
	    }
	}
	elsif($state==$STATE_FILE)
	{
#	    print "SM: FILE: $name\n";
	    # Can't have anything after a filename
	    $self->state($STATE_INVALID);
	}
	elsif($state==$STATE_ALL)
	{
	    if($name eq $PATH_ALLTRACKS)
	    {
		$self->state($STATE_TRACKLIST);
	    }
	    elsif($name eq $PATH_NOARTIST)
	    {
		$self->state($STATE_TRACKLIST);
	    }
	    else
	    {
		my $artist=ID3FS::Path::Node->new($self->{db}, "artist", $name);
		if($artist)
		{
		    push(@{$self->{elements}}, $artist);
		    $self->state($STATE_ALBUMS);
		}
		else
		{
		    $self->state($STATE_INVALID);
		}
	    }
	}
	else
	{
	    print "SM: ERROR: UNKNOWN STATE: $self->{state}\n";
	    $self->state($STATE_INVALID);
	}
    }

    # remove trailing boolean
    my @elements=@{$self->{elements}};
    while(@elements && $self->is("boolean", $elements[$#elements]))
    {
	pop @elements;
    }
    # sort elements by precedence
    @elements=$self->sort_elements(@elements);
    $self->{tagtree}=$self->elements_to_tree(\@elements);
    if($self->{tagtree})
    {
#	my ($conditions, @joins)=$self->{tagtree}->to_sql();
#	print "CONDITIONS(", scalar(@joins), "): ", $conditions, "\n";
    }
}

sub state
{
    my($self, $newstate)=@_;
    if(defined($newstate))
    {
	$self->{state}=$newstate;
	$self->{curtagdepth}++ if($newstate == $STATE_TAG);
    }
    return $self->{state};
}

sub elements_to_tree
{
    my($self, $elements)=@_;
    return undef unless(@$elements);
    my ($left, $right, $op)=(undef, undef, undef);
    my $thing=pop @$elements;
    if($self->is("boolean", $thing))
    {
	$right=$self->elements_to_tree($elements);
	if($thing->{name} ne "NOT")
	{
	    $left=$self->elements_to_tree($elements);
	}
	$thing->left($left);
	$thing->right($right);
    }
    return $thing;
}

# Dijkstra's shunting-yard algorithm
sub sort_elements
{
    my ($self, @input)=@_;
    my @opstack=();
    my @output=();
#    print "INPUT: ", join(', ', map { $_->{name}; } @input), "\n";
    while(my $thing = shift @input)
    {
	if($self->is("tag", $thing))
	{
	    # Handle tag values by dropping parent
	    if(@input && $self->is("tag", $input[0]))
	    {
		$thing=shift @input;
	    }
	    push(@output, $thing);
	}
	elsif($self->is("boolean", $thing))
	{
	    # bool
	    while(@opstack &&
		  ($priorities{$thing->{name}} <= $priorities{$opstack[$#opstack]->{name}}))
	    {
		push(@output, pop(@opstack));
	    }
	    push(@opstack, $thing);
	}
    }
    while(@opstack)
    {
	push(@output, pop(@opstack));
    }
#    print "STACK: ", join(', ', map { $_->{name}; } @output), "\n";
    return @output;
}

sub used_tags
{
    my($self)=@_;
    return() unless(defined($self->{tagtree}));
    return($self->{tagtree}->used_tags());
}

sub expecting_values
{
    my($self)=@_;
    my $tail=$self->tail();
    if($self->is("tag", $tail))
    {
	return($self->{db}->tag_has_values($tail->id()));
    }
}

sub trailing_tag_id
{
    my($self)=@_;
    my $tail=$self->tail();
    if($self->is("tag", $tail))
    {
	return($tail->id());
    }
    return undef;
}

sub trailing_tag_parent
{
    my($self)=@_;
    my $tail=$self->tail();
    if($self->is("tag", $tail))
    {
	return($tail->{parents_id});
    }
    return undef;
}

sub tail
{
    my($self)=@_;
    return($self->{elements}->[$#{$self->{elements}}]);
}

sub at
{
    my($self, $type)=@_;
    return($self->is($type, $self->tail()));
}

sub is
{
    my($self, $type, $thing)=@_;
    return 0 unless($thing);
    return 0 unless($thing->type());
    return 1 if($type eq $thing->type());
    return 0;
}

# the one before last
sub tail_parent
{
    my($self)=@_;
    return($self->{elements}->[($#{$self->{elements}}) - 1]);
}

######################################################################

sub tags
{
    my($self)=@_;
    if(!$self->{tagtree}) # / or /NOT
    {
	my $sql="SELECT DISTINCT name FROM tags WHERE parents_id='';";
	return($self->{db}->cmd_firstcol($sql));
    }
    my $hasvals=$self->expecting_values();
    my $parent=$self->trailing_tag_parent();
#    print "THASVALS: $hasvals\n";
#    print "TPARENT: ", (defined($parent)? $parent : "NO"), "\n";
    my @ids=();
    my $sql=("SELECT tags.name FROM (\n" .
	     $self->tags_subselect() .
	     ") AS subselect\n" .
	     "INNER JOIN files_x_tags ON subselect.files_id=files_x_tags.files_id\n" .
	     "INNER JOIN tags ON files_x_tags.tags_id=tags.id\n");
    my @andclauses=();
    my $id=$self->trailing_tag_id();

    my $parentclause= "tags.parents_id='";
    if($hasvals)
    {
	$parentclause .= $id;
    }
    elsif($parent)
    {
	$parentclause .= $parent;
    }
    $parentclause .= "'";
    push(@andclauses, $parentclause);

    my @used=$self->used_tags();
    if(@used)
    {
	push(@andclauses, "tags.id NOT IN (" . join(', ', @used) . ")");
    }
    if(@andclauses)
    {
	$sql .= "WHERE " . join(' AND ', @andclauses) . "\n";
    }

    $sql .= "GROUP BY tags.name;";
    print "SQL(TAGS): $sql\n" if($self->{verbose});
    my @tagnames=$self->{db}->cmd_firstcol($sql);
    print("SUBNAMES: ", join(', ', @tagnames), "\n") if($self->{verbose});
    return(@tagnames);
}

sub artists
{
    my($self)=@_;
    if(!@{$self->{elements}}) # /ALL
    {
	my $sql="SELECT DISTINCT name FROM artists WHERE name!='';";
	return($self->{db}->cmd_firstcol($sql));
    }
    my @ids=();
    my $sql=$self->sql_start("artists.name");
    $sql .= ("INNER JOIN artists ON files.artists_id=artists.id\n" .
	     "WHERE artists.name != ''\n" .
	     "GROUP BY artists.name;");
    print "SQL(ARTISTS): $sql\n" if($self->{verbose});
    my @tagnames=$self->{db}->cmd_firstcol($sql);
    print("ARTISTS: ", join(', ', @tagnames), "\n") if($self->{verbose});
    return(@tagnames);
}

sub albums
{
    my($self)=@_;
    my @ids=();
    my $tail=$self->tail();
    if($self->is("artist", $tail))
    {
	return $self->artist_albums($tail->id());
    }
    my $sql=$self->sql_start("albums.name");
    $sql .= ("INNER JOIN albums ON files.albums_id=albums.id\n" .
	     "WHERE albums.name != ''\n" .
	     "GROUP BY albums.name;");
    print "SQL(ALBUMS): \n$sql\n" if($self->{verbose});
    my @names=$self->{db}->cmd_firstcol($sql);
    print("ALBUMS: ", join(', ', @names), "\n") if($self->{verbose});
    return(@names);
}

sub artist_albums
{
    my($self, $artist_id)=@_;
    my $sql=$self->sql_start("albums.name");
    $sql .= ("INNER JOIN albums ON albums.id=files.albums_id\n" .
	     "INNER JOIN artists ON artists.id=files.artists_id\n" .
	     "WHERE artists.id=? and albums.name <> ''\n" .
	     "GROUP BY albums.name\n");
    print "ARTIST_ALBUMS SQL: $sql\n" if($self->{verbose});
    my @albums=$self->{db}->cmd_firstcol($sql, $artist_id);
    print("ALBUMS: ", join(', ', @albums), "\n") if($self->{verbose});
    return(@albums);
}

sub artist_tracks
{
    my($self, $artist_id)=@_;
    my $sql=$self->sql_start("files.name");
    $sql .= ("INNER JOIN artists ON artists.id=files.artists_id\n" .
	     "INNER JOIN albums  ON albums.id=files.albums_id\n" .
	     "WHERE artists.id=? AND albums.name=''\n" .
	     "GROUP BY files.name\n");
    print "ARTIST_TRACKS SQL: $sql\n" if($self->{verbose});
    my @names=$self->{db}->cmd_firstcol($sql, $artist_id);
    print("ARTISTTRACKS: ", join(', ', @names), "\n") if($self->{verbose});
    return(@names);
}

sub album_tracks
{
    my($self, $artist_id, $album_id)=@_;
    my $sql=("SELECT files.name FROM files\n" .
	     "INNER JOIN albums  ON albums.id=files.albums_id\n" .
	     "INNER JOIN artists ON artists.id=files.artists_id\n" .
	     "WHERE artists.id=? AND albums.id=?\n" .
	     "GROUP BY files.name\n");
    print "ALBUM_TRACKS SQL($artist_id, $album_id): $sql\n" if($self->{verbose});
    my @names=$self->{db}->cmd_firstcol($sql, $artist_id, $album_id);
    print("TRACKS: ", join(', ', @names), "\n") if($self->{verbose});
    return(@names);
}

sub tracks
{
    my($self)=@_;
    my $tail=$self->tail();
    if($self->is("artist", $tail))
    {
	return $self->artist_tracks($tail->id());
    }
    elsif($self->is("album", $tail))
    {
	my $artist_id=0;
	my $artist=$self->tail_parent();
	if($self->is("artist", $artist))
	{
	    # should always happen
	    $artist_id=$artist->id();
	}
	return $self->album_tracks($artist_id, $tail->id());
    }
    my $sql=$self->sql_start("files.name");
    $sql .= "INNER JOIN artists ON files.artists_id=artists.id\n";
    if($self->{components}->[$#{$self->{components}}] eq $PATH_NOARTIST)
    {
	$sql .= "WHERE artists.name =''\n";
    }
    $sql .= "GROUP BY files.name;";
    print "TRACKS SQL($self->{path}): $sql\n" if($self->{verbose});
    my @names=$self->{db}->cmd_firstcol($sql);
    print("TRACKS: ", join(', ', @names), "\n") if($self->{verbose});
    return(@names);
}

sub filename
{
    my($self, $mountpoint)=@_;
    my $tail=$self->tail();
    if($self->is("file", $tail))
    {
	my $id=$tail->id();
	my $sql=("SELECT paths.name, files.name FROM files\n" .
		 "INNER JOIN paths ON files.paths_id=paths.id\n" .
		 "WHERE files.id=?\n" .
		 "GROUP BY paths.name, files.name");
	print "FILENAME SQL: $sql\n" if($self->{verbose});
	my ($path, $name)=$self->{db}->cmd_onerow($sql, $id);
	my $id3fs_path=join('/', map { $_->{name}; }  @{$self->{elements}});
	return($self->{db}->relativise($path, $name, $mountpoint));
    }
    # should never happen
    return "ERROR";
}

sub tags_subselect
{
    my($self)=@_;
    my $hasvals=$self->expecting_values();
    if($self->{in_all})
    {
	return "\tSELECT id FROM files AS files_id\n";
    }
    my $tree=$self->{tagtree};
    # FIXME
    print "UNDEF!!\n" unless($self->{tagtree});
    my $parent=$self->trailing_tag_parent();

#    print "ELEMENTS: ", join('/', map { $_->{name}; } @{$self->{elements}}), "\n";
#    print "TREE: ", $tree->print(), "\n";
    my $tag=undef;
    if($hasvals)
    {
	$tag=$self->trailing_tag_id();
#	print "Trailing id: $tag\n";
    }
    my ($sqlclause, @joins)=(undef, ());
    ($sqlclause, @joins) = $tree->to_sql($hasvals) if($tree);
#    print "SQL(" . scalar(@joins) ."): $sqlclause\n";
    my $sql="\tSELECT fxt1.files_id FROM tags t1";
    my @crosses=();
    my @inners=();
#    $joinsneeded++ if($tag);
    for(my $i=0; $i <= $#joins; $i++)
    {
	my $cnt=$i+1;
	my $join=$joins[$i];
	my $inner=("\t$join JOIN files_x_tags fxt$cnt ON " .
		   "t${cnt}.id=fxt${cnt}.tags_id");
	if($i > 0)
	{
	    push(@crosses, "CROSS JOIN tags t$cnt");
	    $inner .= " AND fxt1.files_id=fxt${cnt}.files_id";
	}
	push(@inners, $inner);
    }
    $sql .= ("\n\t" . join(" ", @crosses)) if(@crosses);
    $sql .= ("\n" . join("\n", @inners)) if(@inners);
    $sql .= "\n\tWHERE $sqlclause" if($sqlclause);
#    if($tag)
#    {
#	$sql .= " AND t${joinsneeded}.parents_id='$tag'";
#    }
    $sql .= "\n\tGROUP BY fxt1.files_id\n";
    return $sql;
}

sub sql_start
{
    my($self, $tables)=@_;
    my $sql="SELECT $tables FROM ";
    if($self->{in_all})
    {
	$sql .= "files\n";
    }
    else
    {
	$sql .= ("(\n" .
		 $self->tags_subselect() .
		 ") AS subselect\n" .
		 "INNER JOIN files ON subselect.files_id=files.id\n");
    }
    return $sql;
}


sub constraints_tag_list
{
    my($self, @constraints)=@_;
    my $lasttag=undef;
    my @tags=();
    my @tags_vals=();
    for my $constraint (@constraints)
    {
#	print ref($constraint), ": ", $constraint->{name}, "\n";
	if($self->is("tag", $constraint))
	{
	    if(defined($lasttag))
	    {
#		print "TAGVAL\n";
		push(@tags_vals, [$lasttag, $constraint->id()]) if defined($constraint->id());
		$lasttag=undef;
	    }
	    elsif($self->tag_has_values($constraint->id()))
	    {
#		print "HASVALUES\n";
		$lasttag=$constraint->id() if defined($constraint->id());
	    }
	    else
	    {
#		print "NOVALUES\n";
		push(@tags, $constraint->id()) if(defined($constraint->id()));
	    }
	}
    }
    @tags=map{ "\"$_\""; } @tags;
    @tags_vals=map( { [ map({ "\"$_\""; } @$_ ) ] } @tags_vals);
    $lasttag="\"$lasttag\"" if defined($lasttag);
    return(\@tags, \@tags_vals, $lasttag);
}

# we just filter $ALLTRACKS, $NOARTIST and $NOALBUM
# filtering tags properly requires up to four levels of recursion
# (tag/tagval/AND/NOT) and is too slow
sub filter
{
    my($self, @dirs)=@_;
    my $base=$self->{path};
    my @outdirs=();
    for my $dir (@dirs)
    {
#	print "\nFILTER (",$self->state(), "): $base / $dir\n";
	if($self->empty("$base/$dir"))
	{
#	    print "empty: $base / $dir\n";
	}
	else
	{
#	    print "non-empty, accepting: $base / $dir\n";
	    push(@outdirs, $dir);
	}
    }
    return(@outdirs);
}

sub empty
{
    my($self, $dir)=@_;
    my $path=ID3FS::Path->new($self->{db}, $dir, $self->{verbose},
			      ($self->{maxtagdepth} - $self->{curtagdepth}));
    return 1 unless($path->isvalid());
    my($subdirs,$subfiles)=$path->dirents();
    return 0 if(@$subfiles || @$subdirs);
    return 1;
}

1;
