package Possum::Tags;

use strict;
use warnings;
use DBI;
use Cwd;

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

	# TODO: Read config... for now, just use $HOME/.ptags/tags as database
	# NOTE: Can be insecure, if people set $HOME to random values(?)
	my $db = $ENV{HOME}.'/.ptags/tags';
	# Set dbh
	$self->dbh("dbi:SQLite:$db");
	return $self;
}

sub dbh {
	my $self = shift;
	$self->{DBH} = DBI->connect(shift) if @_;
	return $self->{DBH};
}

sub build_table {
	my $self = shift;
	# Currently VERY inneficient...
	# File names stored with abs_path()
	my $sth = $self->dbh->prepare(<<SQL);
CREATE TABLE IF NOT EXISTS tags (
	id	INTEGER PRIMARY KEY AUTOINCREMENT,
	filename	TEXT,
	tag	TEXT,
	UNIQUE (filename,tag)
);
SQL
	$sth->execute or warn $self->dbh->errstr;
}

sub add_tag {
	# Tags file $_[1] with tag $_[2 .. $#_]
	my ( $self, $filename, @tags ) = @_;
	$filename = Cwd::abs_path($filename);
	my $sth = $self->dbh->prepare(
		'INSERT INTO tags (filename,tag) VALUES(?,?)');
	foreach my $tag (@tags) {
		$sth->execute($filename,$tag) or warn $self->dbh->errstr;
	}
	return 1;
}

sub tags_full_path {
	# Get all tags for file $_[1]
	# Returns as array ref of tags
	my ( $self, @filenames ) = @_;
	my %out;
	my $sth = $self->dbh->prepare(
		'SELECT tag FROM tags WHERE filename=?');
	foreach my $filename (@filenames) {
		$filename = Cwd::abs_path($filename);
		$sth->execute($filename) or warn $self->dbh->errstr && return;
		while ( my @row = $sth->fetchrow_array ) {
			push (@{ $out{$filename} }, shift(@row));
		}
	}
	return \%out;
}

sub get_tags {
	# Get tags for a single file
	my ( $self, $filename ) = @_;
	my @out;
	my $sth = $self->dbh->prepare('SELECT tag FROM tags WHERE filename=?');
	$filename = Cwd::abs_path($filename);
	$sth->execute($filename) or warn $self->dbh->errstr && return;
	while ( my @row = $sth->fetchrow_array ) {
		push (@out, shift(@row) );
	}
	return \@out;
}

sub all_with_tag {
	# Takes one tag as argument
	# EXACT MATCHES ONLY
	# returns array ref
	my ( $self, $tag_name ) = @_;
	my @out;
	my $sth = $self->dbh->prepare('SELECT filename FROM tags WHERE tag=?');
	$sth->execute($tag_name) or warn $self->dbh->errstr && return;
	while ( my @row = $sth->fetchrow_array ) {
		push (@out, shift(@row) );
	}
	return \@out;
}

1;
