package ACIS::Web::LogOff;

##  This is part of ACIS software.
##
##  This module is responsible for closing old (left) sessions.
## 


use strict;

use Data::Dumper;
use Carp::Assert;


use ACIS::Data::DumpXML qw( dump_xml );
use ACIS::Data::DumpXML::Parser;

use ACIS::Common;

use ACIS::Web::Session;


sub user_normal_logoff {

  my $app = shift;

  assert( $app );

  my $session = $app -> session; 

  if ( $session -> type ne 'user' ) {
    $app -> error( 'session-wrong-type' );
    return;
  }

  logoff( $app );
}


sub new_user_logoff {  ### in fact, confirm

  my $app = shift;

  assert( $app );

  my $session = $app -> session; 

  if ( $session -> type ne 'new-user' ) {
    $app -> error( 'session-wrong-type' );
    return;
  }

  logoff( $app );
}



sub logoff {

  debug "processing logoff service screen";
  
  my $app = shift;

  assert( $app );

  my $homedir = $app ->{home};

  my $session = $app -> session; 
  my $paths   = $app -> paths;
  my $config  = $app -> config;

  my $mode = $session -> type;

  $app ->userlog ( "log off" );

  my $udata_file = $paths ->{'user-data-old'};  ### XXX not necessarily from there

  my $udata_string;
  my $udata_real;


  ### first we compare the copy of userdata in session and in file


  assert( $udata_file, "user-data file name is absent" );
  
  if ( $mode eq 'user'  
       and ( -f $udata_file ) ) {

    assert( -f $udata_file );

    open USERDATA, "<:utf8", $udata_file;  ### XXX PERL5.8 dependency
    
    my $irs = $/; undef $/;
    
    $udata_string = <USERDATA>;
    close USERDATA;
    
    $/ = $irs;
    
    $udata_real  = ACIS::Data::DumpXML::Parser ->new ->parse( $udata_string );
    debug "loaded old userdata file and parsed it";
    
  } else {
    debug "there's no old user-data file";
    ###  that would happen for all new users

    $udata_string = '';
  } 


  my $udata_records = {};

  if( $udata_real ) {
    foreach ( @{ $udata_real->{records} } ) {
      my $id = $_ ->{id};
      if( $id ) {
	$udata_records->{$id} = $_;
      }
    }

  }

  my $ses_udata        = $session ->{'user-data'};
  my $ses_udata_string = $ses_udata -> dump_xml;


  my @profiles = ();

  ### check for changes in userdata

  debug 'comparing the userdatas';

  if ( $mode eq 'new-user' 
       or $ses_udata_string ne $udata_string )   {
    debug 'found some changes';

    $app -> success( 1 );


    my $static_url = $app ->{static};
    my $static_dir = $app ->{shared};


    my $number = 0;

    foreach my $record ( @{ $ses_udata ->{records} } ) {

      my $id = $record ->{id};

      if( $record ->{type} eq 'person' ) {
	
	my $sid   = $record ->{'short-id'};


	### update the personal profile

	if( $sid ) {
	  my $link = &write_outside_personal_profile( $app, $number );

	  push @profiles, { name => $record->{'full-name'}, 
			    link => $link };

	}
				 

	###  has this record changed recently?  
	
#	my $orig_record   = $userdata_records ->{$id};
#	my $record_string = dump_xml( $record );

	###  if so, notify the person it is about (by email)
	###  (of course, if we have the email)



      } # if type == "person"



    } continue {
      $number ++;

    } # foreach of the records in session



    ###  process userdata owner login change
   
    my $owner = $ses_udata -> {owner};
    
    if ( $owner -> {'old-login'} ) {

      $app -> userlog ( "log off: login change from ", 
			$owner->{login},
			" to ", 
			$owner->{'old-login'} );

      $app -> send_mail ( 'email/user-login-changed.xsl' );

      debug 'old userdata file is: ' . $udata_file . ' trying to delete it';
      
      unlink $udata_file;
      delete $owner -> {'old-login'};
    }
    

    # notify the user, that her changes are taken into account
    if( $mode eq 'user' ) {
      $app -> send_mail ( 'email/user-data-changed.xsl' );

    } elsif( $mode eq 'new-user' ) {
      ### XXX send some other email?

    }


    ###  save the userdata
    
    $session -> {'user-data'} -> save ( $paths -> {'user-data'} );

    $app -> userlog ( "log off: wrote ", $paths->{'user-data'} );
    
    $app -> variables -> {'saved-profiles'} = \@profiles ;
    

    ###  XXX write out the metadata

    
  } else {
    debug "no changes to save";
    $app -> userlog ( "log off: no changes to save" );
  }
  

  my $submitted = $session -> {'submitted-institutions'};
  foreach ( @$submitted ) {
    $app -> variables -> {institution} = $_;
    $app -> send_mail ( 'email/new-institution.xsl' );
  }


  $session -> close;



  ###  Show user something? 
}




sub write_outside_personal_profile {

  my $app    = shift;
  my $rec_no = shift;

  my $session = $app ->session;
  $session -> {'current-record-number'} = $rec_no;

  my $record = $session ->current_record;


  my $paths  = $app->paths;

  my $static_url     = $paths ->{static};
  my $static_dir     = $paths ->{shared};


  assert( $record ->{type} eq 'person' );

  my $sid   = $record ->{'short-id'};
  assert( $sid );


  debug 'writing out the profile';


  my $variables = $app ->variables;

  $variables ->{record} = $record;


  ###  prepare affiliations 
  $variables ->{affiliations} = undef;

  use ACIS::Web::Affiliations;

  ACIS::Web::Affiliations::prepare( $app );


  ###  prepare contributions 
  $variables ->{contributions} = undef;



  ###  prepare photo

  my $profile_file = "$static_dir/$sid.html";
  my $profile_url  = "$static_url/$sid.html";


  if( $record->{photo} ) {
    $variables ->{photo}     = $record ->{photo} {url};
  }

  $record -> {profile}{url}  = $profile_url;
  $record -> {profile}{file} = $profile_file;

  $variables ->{permalink}   = $profile_url;
	
  debug "profile file: $profile_file";
  debug "profile url : $profile_url";


  ### generate the page

  my $template = 'person-profile.xsl';


  debug Dumper $app ->{'presenter-data'};


  my $page = $app -> run_presenter( $template, 1 );   

  if (open HTML, '>:utf8 ', $profile_file ) {
    print HTML $page;
    close HTML;

    $app -> userlog ( "log off: wrote $profile_file" );
    
  } else {
    $app -> errlog ( "Can't write profile page to $profile_file" );
    $app -> error ('outside-profile-cannot-store');
  }

  debug "profile page contains ". length( $page ) . " chars";
 
  ### clean up after myself

  delete $variables ->{record};
  delete $variables ->{affiliations};
  delete $variables ->{contributions};
  delete $variables ->{photo};
#  delete $variables ->{permalink};

  return $variables ->{permalink};
}



1;
