package ACIS::Web::User;

use strict;
use warnings;

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

use CGI::Untaint;

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

use ACIS::Web::Affiliations;



sub login
 {
  debug "running login user screen";
  
  my $self = shift;
  
#  $self -> redirect_to_screen ('welcome');
 }



sub welcome {  ### XXX do we need this? doubtful
  debug "running initial user screen";
  
  my $self = shift;
  
  debug Dumper $self;
  
}

# все введенные пользователем данные хранятся в $acis_web -> {entered-user-data}
# все найденные ошибки заносятся в список ошибок ($acis_web -> {errors}) в виде:
# [error-context, error-type]
# как пример, ошибка парсинга поля формы будет занесена как
# [screen-name/param-name, form-field/error-text]
# а ошибка mysql как
# [database, query-type/error-text]


sub personal_data_init {
  my $self = shift;
  
  $self -> set_form_value ('name-variations',
   join ("\n", @{$self -> session -> current_record -> {'name-variations'}}));
}



sub personal_data {
  my $self = shift;
  
  debug "running personal data screen";
  
  my $variations = $self -> get_form_value ('name-variations');

  $variations =~ s/ +/ /gs;
  $variations = [split (/\s*[\n\r]+/, $variations)];
  
  my $session = $self -> session;
  my $record  = $session -> current_record;
  my $owner   = $session -> owner;
  
  $record -> {'name-variations'} = $variations;

  if ( 
      $record -> {'about-owner'} 
      and $record -> {'about-owner'} eq 'yes'
      and (
	   not $owner -> {type} 
	   or $owner -> {type} ne 'advanced' 
	   )
     ) {
      
    ### simple user mode
    
    my $login = $record -> {email};
    my $full_name = $record -> {'full-name'};
    
    if ( $owner -> {name} ne $full_name ) {
      $owner -> {name} = $full_name;
    }
    
    if ( $login ne $owner -> {login} ) {
      if ( not defined $owner -> {'old-login'} ) {
	$owner -> {'old-login'} = $owner -> {login};
      }
      $owner -> {login} = $login;
    }
  }
  
  $self -> redirect_to_screen ('welcome');
}




sub upload_photo {

  debug "upload photo screen";
  
  my $self = shift;

  my $session = $self -> session;
  my $request = $self -> request;
  my $record  = $session -> current_record;
  my $query   = $request -> {CGI};
  
  $CGI::POST_MAX = 2097152;  #;-)
  
  my $url  = $self -> paths -> {'personal-url'};
  my $path = $self -> paths -> {'personal-path'};
  
  my $photo = $record ->{photo};

  if ( $photo
       and $photo -> {file}
       and -f $photo -> {file}
     ) {
    $self -> variables -> {photo} = $photo ->{url};
  } 
  
  return unless $query -> param ( 'photo' );
  
  my $file = $query -> upload( 'photo' );
  if ( !$file && $query -> cgi_error ) {
    $self -> error( 'photo-cgi-error' ); #$query -> cgi_error;
    return;
  }

  $file =~ m/^.*\.([^.]+)$/;  
  my $extension = $1;
  if ( not $extension
       or $extension !~ /^(jpe?g|gif|png|bmp)$/i ) {
    $self -> error ('photo-image-unknown-format');
    $self -> clear_process_queue;
    return;
  }
  
  debug "try to save file into '$path$extension'";
  
  my $out_file = "$path$extension";
  if ( open PHOTO, '>', $out_file ) {
    binmode PHOTO;
    my $buffer;
    while ( read ($file, $buffer, 1024) ) {
      print PHOTO $buffer;
    }
    close PHOTO;

    $self -> userlog ( "uploaded a photo image file ($out_file)" );
    
  } else {

    $self -> errlog ( "can not save uploaded photo to a file: $out_file" );
    $self -> error ('photo-cannot-open-file');
    return;
  } 

  if ( not $record -> {photo} 
       or not ref $record->{photo} ) {
    $photo = $record ->{photo} = {};
  }

  $photo -> {ext}  = $extension;
  $photo -> {file} = $out_file;
  $photo -> {url}  = "$url$extension";
  
  $self -> redirect_to_screen ( 'welcome' );
}






sub sci_fields {

  debug "running sci-fields service screen";
  
  my $self = shift;
  
  $self -> redirect_to_screen ('welcome');

}






sub unregister {   

  my $self = shift;

  my $paths = $self -> paths;
    
  my $session  = $self -> session;

  
  if( not defined $self -> get_form_value( 'confirm-it' ) ) {
    ### request the confirmation 
    return ;
  }

  $self-> userlog( "removing the account, per user request" );


  my $userdata = $paths -> {'user-data'};
  my $deleted_userdata = $paths -> {'user-data-deleted'};
  
  debug "move userdata from '$userdata' to '$deleted_userdata'";


  ### XXX shouldn't it be instead a kind of log-off ???

  ### XXX no security check for the file overwrite
  my $check = rename $userdata, $deleted_userdata;  

  if ( not $check ) {
    $self -> errlog ( "Can't move $userdata file to $deleted_userdata" );
    $self -> error ( "cant-remove-account" );
    return;
  }


  ### XXX send update request to the RI UD (RePEc-Index Update Daemon)

  ### XXX delete the profile pages

  my $udata = $session -> {'user-data'};
  
  foreach ( @{ $udata-> {records} } ) {
    my $file = $_->{'profile-file'};

    if( $file and -f $file ) {
      unlink $file;
      $self-> userlog( "removing profile file at $file" );
    }

  }
    
  $self -> send_mail ( 'email/account-deleted.xsl' );

  $self -> userlog ( "deleted account; backup stored in $deleted_userdata" );
    
  debug "close the session";
  $session -> close;
  $self -> {session} = undef; 

  $self -> message ( 'account-deleted' ); ### XXX what for if there is a redirect later?

  $self -> success( 1 );

  $self -> redirect ( $self -> config( 'base-url' ) );
   
}



sub profile_overview {
  my $self = shift;
  
  $self -> variables -> {record} = $self -> session -> current_record();

  ACIS::Web::Affiliations::prepare( $self );
}





sub normal_login {

  my $app = shift;

  my $login = $app -> get_form_value( 'login' );
  my $success;

  if( $login ) {
    $success = ACIS::Web::authenticate( $app ); 
    if( $success ) {
      $app -> redirect_to_screen( 'welcome' );
    }
  }

}



sub check_session_type {
  my $app = shift;
  
  my $session = $app -> session;
  
  if( $session -> type ne 'user' ) {
    $app -> error( 'session-wrong-type' );
    $app -> set_presenter( 'sorry' );
    $app -> clear_process_queue();
  }

}


sub new_institution {
  my $app = shift;
  
  $app -> send_mail ('email/new-institution.xsl');
  
  $app -> redirect_to_screen ( 'affiliation');
}




1;
