package Daje::Plugin::Input::ConfigManager;
use Mojo::Base -base, -signatures;


our $VERSION = "0.01";

use Daje::Plugin::Database::SqlLite;
use Daje::Plugin::Database::Operations;
use Daje::Tools::Filechanged;

use Mojo::File;
use Mojo::JSON qw{from_json};

has 'source_path';
has 'files';
has 'filetype' ;
has 'changed_files' ;
has 'change';

sub save_new_hash($self, $file) {
    my $path = Mojo::File->new($file);
    my $new_hash = $self->change->load_new_hash($path);
    my $dbh = Daje::Plugin::Database::SqlLite->new(path => $path)->get_dbh();
    my $operations = Daje::Plugin::Database::Operations->new(dbh => $dbh);
    $operations->save_hash($path->dirname . '/' . $path->basename, $new_hash);

    return 1;
}

sub load_json($self, $file) {
    my $context;
    eval {
        $context =  Mojo::File->new($file)->slurp;
    };
    die "load_json failed '$@" if $@;

    return from_json($context);
}

sub load_changed_files ($self) {
    my ($dbh, $operations, $path) = $self->_load_objects();
    eval {
        $self->files($path->list());
    };
    die "Files could not be loaded: $@" if $@;

    my $length = scalar @{$self->files};
    for (my $i = 0; $i < $length; $i++) {
        my $old_hash = $operations->load_hash(@{$self->files}[$i]->dirname . '/' . @{$self->files}[$i]->basename);
        if ($self->change->is_file_changed( @{$self->files}[$i], $old_hash)) {
            push @{$$self->changed_files}, @{$self->files}[$i]->dirname . '/' . @{$self->files}[$i]->basename;
        }
    }
    return;
}

sub _load_objects($self) {
    my $path = Mojo::File->new($self->source_path);
    $self->change(Daje::Tools::Filechanged->new());
    my $dbh = Daje::Plugin::Database::SqlLite->new(path => $path)->get_dbh();
    my $operations = Daje::Plugin::Database::Operations->new(dbh => $dbh);

    return ($dbh, $operations, $path);
}

1;

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

=head1 NAME

Daje::Plugin::Input::ConfigManager


=head1 DESCRIPTION

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


=head1 REQUIRES

L<Mojo::JSON> 

L<Mojo::File> 

L<Daje::Tools::Filechanged> 

L<Daje::Plugin::Database::Operations> 

L<Daje::Plugin::Database::SqlLite> 

L<Mojo::Base> 


=head1 METHODS

=head2 load_changed_files

 load_changed_files();

=head2 load_json($self,

 load_json($self,();

=head2 save_new_hash($self,

 save_new_hash($self,();


=cut

