package Dancer2::Plugin::SessionDatabase;

use Modern::Perl;
use Dancer2::Plugin; 
use Dancer2::Plugin::Database;
require Dancer2::Session::DatabasePlugin;
use Carp qw(croak);

=head1 NAME

Dancer2::Plugin::SessionDatabase - Hook Loader For Dancer2::Session::DatabasePlugin

=head1 DESCRIPTION

Hook loader for Dancer2::Session::DatabasePlugin.

=cut

# This method runs after the new constructor
sub BUILD {
  my ($self)=@_;

  $self->app->add_hook(
    Dancer2::Core::Hook->new(
      name=>"engine.session.beforedb",
      code=>sub { 
        my $session=$self->get_session;
        my $dbh=database($session->connection)
	  or croak qq{Looks like "$session" is not a valid conneciton for Dancer2::Plugin::Database, check your config.yml in:
  engines:
    session:
      DatabasePlugin:
	connection: "$session"};
	  $session->dbh($dbh);
	}  
      )
  );
  $self->app->add_hook(
    Dancer2::Core::Hook->new(
      name=>"database_connection_lost",
      code=>sub { 
	my ($dbh)=@_;
          $self->reset_session($dbh);
        }
      )
  );
  $self->app->add_hook(
    Dancer2::Core::Hook->new(
      name=>"database_error",
      code=>sub { 
	my ($err,$dbh)=@_;
          $self->reset_session($dbh);
      }
    )
  );
  $self->app->add_hook(
    Dancer2::Core::Hook->new(
      name=>"database_connected",
      code=>sub { 
        my ($dbh)=@_;
	my $session=$self->get_session;
	my $cmp=$session->dbh;
	return unless defined($cmp);

	# stop here if the new connection is not our connection
	return if $cmp ne $dbh;

	# clean things up!
	$session->dbh($dbh);
        %{$session->sth_cache->{$session->connection}}=();
      }
    )
  );
}

sub reset_session {
  my ($self,$dbh)=@_;
  my $session=$self->get_session;
  return unless defined($session->dbh);
  return unless $session->dbh eq $dbh;

  delete $session->{dbh};
  # force our statement handle cache to be reset
  %{$session->sth_cache->{$session->connection}}=();
}

sub get_session { $_[0]->app->engine('session') }

=head1 AUTHOR

Michael Shipper AKALINUX@CPAN.ORG

=cut

1;
