package Platform::Session;
use base 'Platform::DBI';
use strict;
use warnings;
use Apache2::Cookie;
use YAML::XS;

__PACKAGE__->table('session');
__PACKAGE__->sequence('session_session_seq');
__PACKAGE__->columns( Primary => 'session' );
__PACKAGE__->columns( Essential => qw / cookie account tickle stash / ) ;
__PACKAGE__->columns( TEMP => qw ( apache mason cache ) );

__PACKAGE__->has_a(account => q(Platform::Account));
__PACKAGE__->has_a(stash => q(Platform::Hash), inflate => sub { Load(shift) }, deflate => 'dump');

__PACKAGE__->add_trigger(before_create => \&_initialize_stash);
__PACKAGE__->add_trigger(before_update => \&_dirty_stash);


sub _initialize_stash {
  my ($session) = @_;

  $session->{stash} ||= bless { }, 'Platform::Hash';
}

sub _dirty_stash {
  my ($session) = @_;

  $session->stash($session->stash);
}

sub write {
  my ($session) = @_;

  my $cookie = Apache2::Cookie->new( $session->apache,
				    -name => 'session',
				    -value => $session->cookie ,
				    -path => '/',
				  );

  $cookie->bake($session->apache);
}

sub From_cookies {
  my ($class) = @_;
  my %cookies = Apache2::Cookie->fetch;
  my $session;

  Platform::Session->db_Main->do("DELETE FROM ${\$class->table} WHERE tickle < NOW() - ?::INTERVAL", { }, $Platform::CONFIG->{common}{session_timeout});

  if (my $cookie = $cookies{session}) {
    ($session) = Platform::Session->search(cookie => $cookie->value);
  }

  return $session;
}

sub create {
  my $session = shift->SUPER::create(@_);
  $session->write;
  return $session;
}

sub reset_stash {
  my ($session) = @_;

  $session->stash(bless { }, 'Platform::Hash');
}

