package ID3FS::DB;

use strict;
use warnings;
use DBI;
use ID3FS::File;

our $SCHEMA_VERSION=1;

my $dbfile=".id3fs";

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

    my($dir, $init, $me)=@_;
    $self->{dbpath}="$dir/$dbfile";
    $self->{me}=$me;

    my $exists=-f $self->{dbpath};
    die("$me: $self->{dbpath}: not found. use --init to create.\n") if(!$exists && !$init);
    die("$me: --init used but $self->{dbpath} exists.\n")           if($exists && $init);

    $self->{dbh}=DBI->connect("dbi:SQLite:dbname=$self->{dbpath}","","",
			      { AutoCommit=>1 } );
    unless(defined($self->{dbh}))
    {
	die("$me: DB Error: " . $DBI::errstr . "\n");
    }

    if($init)
    {
	$self->create();
    }
    else
    {
	$self->checkschema();
    }

    return $self;
}

sub create
{
    my($self,$name)=@_;
    my @schema=split(/\n\n/,join("", <DATA>));
    close(DATA);
    for my $cmd (@schema)
    {
	$self->{dbh}->do($cmd);
    }
    $self->cmd("INSERT INTO id3fs (schema_version) VALUES (?)", $SCHEMA_VERSION);
}

sub checkschema
{
    my $self=shift;
    my ($version)=$self->cmd_onerow("SELECT schema_version from id3fs");
    if(!defined($version) || $version != $SCHEMA_VERSION)
    {
	die("$self->{me}: id3fs database version " .
	    defined($version) ? $version : '""' .
	    "not known, current version is $SCHEMA_VERSION.\n");
    }
}

sub cmd_sth
{
    my($self, $sql, @params)=@_;
    my $sth=$self->{dbh}->prepare($sql);
    my $idx=1;
    for my $param (@params)
    {
	$param="" unless(defined($param));
	$sth->bind_param($idx++, $param);
    }
    $sth->execute();
    return $sth;
}

sub add
{
    my($self,$path)=@_;
    my $file=ID3FS::File->new($path);
}

sub cmd
{
    my ($self, @args)=@_;
    # don't care about retcode
    $self->cmd_sth(@args);
}

sub cmd_onerow
{
    my ($self, @args)=@_;
    my $sth=$self->cmd_sth(@args);
    return($sth->fetchrow_array());
}

__DATA__

CREATE TABLE id3fs (
    schema_version
);

CREATE TABLE files (
    id INTEGER PRIMARY KEY,
    path
);

CREATE TABLE tags (
    id INTEGER PRIMARY KEY,
    name
);

CREATE TABLE tags_x_files (
    files_id,
    tags_id
);

CREATE TABLE v1genres (
   id,
   name
);
