package ARDB::ReDIF::Processing;


sub extract_creation_date {
  my $record = shift;

  my ($date) = $record -> get_value( "creation-date" );

  if( $date =~ /^\d{4}\-\d{2}$/ ) {
    $date = "$date-00";
  } elsif ( $date =~ /^\d{4}$/ ) {
    $date = "$date-00-00";
  } else {
    return "0000-00-00";
  }
  return $date;
}

sub extract_revision_date {
  my $record = shift;
  my ($date) = $record -> get_value( "revision-date" );
  if( $date =~ /^\d{4}\-\d{2}$/ ) {
    $date = "$date-00";
  } elsif ( $date =~ /^\d{4}$/ ) {
    $date = "$date-00-00";
  } else {
    return "0000-00-00";
  }
  return $date;
}


sub extract_part_of_relationships {
  my $ARDB   = shift;
  my $record = shift;

  # get the series part or the archive part of the handle

  my $id = $record->id;
  my $colons = $id =~ s/:/:/g;

  my $part_of;

  if( $colons == 1 ) { # archive 
    return;

  } elsif( $colons == 2 ) {
    my ( $archive ) = $id =~ /^([^:]+:[^:]+):/ ;

    $part_of = $archive;

  } elsif( $colons > 2 ) {
    my ( $series )  = $id =~ /^([^:]+(?::[^:]+){2}):/ ;

    $part_of = $series;    
  }

  if( $part_of ) {
    my $relations = $ARDB->relations;

#    print "$id is part of $part_of\n";
    $relations -> store ( [ $id, 'part-of', $part_of, $id ] );

  } else {
#    print "$id is not part of anything\n";
  }
}


use Carp::Assert;

sub extract_author_names {
  my $record = shift;

  assert( $record );
  
  my @au = $record -> get_value( "author/name" );

  return ( join( "\x1", @au ) );
}


sub short_lc_record_type {
  my $record = shift;
  
  my $t = $record -> type;
  $t =~ s/(ReDIF-)//i;
  $t =~ s/\s*1.0//;

  $t = lc $t;
}


package ARDB::ReDIF::Processing::Fire;

sub authors {
  my $record = shift;

  my @au = $record -> get_value( "author/name" );

  return ( join( " &: ", @au ) );
}

sub urls {
  my $record = shift;

  my @f = $record -> get_value( "file" );
  my $res = '';

  foreach ( @f ) {
    my $type = uc $_->{format}->[0];
    $type =~ s/^application\///i;
    $type =~ s#/#-#g;

    if ( not $type ) { $type = 'FILE' };

    my $url  = $_->{url }->[0];
    $res .= "$type $url &";
  }

  return $res;
  
}

sub file {
  my $record = shift;

  if( scalar $record -> get_value( "file" ) ) {
    return 1;
  } else {
    return 0;
  }
}

sub jel {
  my $record = shift;

  my @l = $record -> get_value( "classification-jel" );

  return ( join( ", ", @l ) );

}

use ARDB::Common;

sub conditional_content_ft_store {
  my $ARDB   = shift;
  my $record = shift;

  my @f = $record->get_value( 'file' );

  return if not scalar @f;

  my $config     = $ARDB -> {'config'};
  my $sql_object = $ARDB -> {'sql_object'};

  my $map        = $config -> mapping ( 'fire_documents' );

  critical "map 'fire_documents' is absent"
    if ( not $map );

  my $table_record = $map -> produce_record( $record );
  $config -> table( 'Fire.content_ft' ) -> store_record( $table_record, $sql_object );
}


1;

