package Daje::Plugin::Database::SqlLite;
use Mojo::Base -base, -signatures;

use DBI;

has 'dbh' ;
has 'data_dir';
has 'path';
has 'open' => 0;

sub get_dbh($self) {

    unless ($self->open) {
        $self->_open_database();
    }
    return $self->dbh();
}

sub _open_database($self) {
    my $new = $self->_datadir();
    $self->_open();
    $self->_add_table();
}

sub _add_table($self){
    my $script = $self->_table_script();
    my $sth = $self->dbh->prepare($script)
        or die "Couldn't create table: " . $self->dbh->errstr;
    $sth->execute()
        or die "Couldn't create table: " . $self->dbh->errstr;
}

sub _open($self){
    my $dbfile = $self->data_dir .'/generate.db';
    my $dbh = DBI->connect("dbi:SQLite:dbname=$dbfile","","",
        {
            PrintError => 1, AutoCommit => 1
        }
    ) or die $DBI::errstr;

    $self->dbh($dbh);
    $self->open(1);
}

sub _datadir($self) {
    my $new = 0;
    eval {
        $self->data_dir($self->path->dirname . "/data");
        if (!(-d $self->data_dir)) {
            mkdir("$self->data_dir", 0700);
            $new = 1;
        }
    };
    die "Failed creating datadir '$@" if $@;
    return $new
}

sub _table_script($self) {
    return qq{
            CREATE TABLE IF NOT EXISTS file_hashes (
                file text PRIMARY KEY,
                hash text NOT NULL,
                moddatetime text
            );
        };
}


1;

#################### pod generated by Pod::Autopod - keep this line to make pod updates possible ####################

=head1 NAME

Daje::Plugin::Database::SqlLite


=head1 DESCRIPTION

pod generated by Pod::Autopod - keep this line to make pod updates possible ####################


=head1 REQUIRES

L<DBI> 

L<Mojo::Base> 


=head1 METHODS

=head2 get_dbh($self)

 get_dbh($self)();


=cut

