package ACIS::Web::Admin;

use strict;
use ACIS::Common;
use Data::Dumper;
use ACIS::Data::DumpXML qw(dump_xml);


use Storable qw( &retrieve );

my $current_time = time;


sub show_sessions {
  my $acis = shift;

  my $home = $acis ->{paths} ->{home};
  my $sessions_dir = "$home/sessions";
  
  opendir SES, $sessions_dir;
  my @sessions = readdir SES;
  closedir SES;

  my @sl;
  
  foreach ( @sessions ) {
    my $id = $_;
    my $filename = "$sessions_dir/$_";
    next if not -f $filename or not -r _;
    
    my @filestat = stat $filename;

    my $mtime = $filestat[9];

    my $difference = $current_time - $mtime;  # in seconds


    my $about = {
		 id => $id,
		 filename => $filename,
		 diff => $difference,
		 };

    my $loaded;
    eval {
      $loaded = retrieve ($filename);
    };
    if( not $@ and defined $loaded ) {

      my $name;

      if( $loaded -> owner ->{name} ) {
	$name = $loaded -> owner -> {name};
      } else {
	$name = $loaded -> {'user-data'} {name};
      }

      $about->{owner} = $name;

      push @sl, $about;
    }
    
  }



  $acis->variables->{'session-list'} = \@sl;

}



use CGI qw( :standard );

sub session_act {
  my $acis = shift;

  my $home = $acis->{paths}->{home};
  my $sessions_dir = "$home/sessions";

  my $id = param('id');

  if( not $id 
      or ( $id =~ m!(/|\.)!g )
    ) {
    $acis->{error} = "id-bad-or-missing";
    return undef;
  }

  my $filename = "$sessions_dir/$id";
  die "No session file: $filename" if not -f $filename or not -r _;
  
  my @filestat = stat $filename;
  
  my $mtime = $filestat[9];
  
  my $difference = $current_time - $mtime;  # in seconds
  
  my $about = {
	       id => $id,
	       filename => $filename,
	       diff => $difference,
	      };
  
  my $loaded;
  eval {
    $loaded = retrieve ($filename);
  };
  if( not $@ and defined $loaded ) {
    $acis->variables->{se} = $about;

    if( $loaded->{owner}->{name} ) {
      $acis->variables->{se} -> {owner} = $loaded->{owner};

    } else {
      $acis->variables->{se} -> {owner} = $loaded->{'user-data'}{owner};
    }      
#    $acis->variables->{se} -> {contents} = $loaded;

    use Data::Dumper;
#    my $session_text = dump_xml( $loaded );
    my $session_text = Dumper( $loaded );
    
    $acis->variables->{se} -> {text} = $session_text;
    
  }  

  
}


1;
