package CPULoadTextPlugin;

use TextPlugin;

use strict;
no strict 'refs'; # allow filehandles to be variables and viceversa
no strict 'subs';

sub BEGIN
{
  @CPULoadTextPlugin::ISA = ('TextPlugin');

  eval('use Crypt::Blowfish_PP');
  if ($@)
  {
    # We need the Perl version before continuing
    if (!defined $ENV{'PERL_VERSION'})
    {
      $ENV{'PERL_VERSION'} = `perl -S $ENV{'GEXTPARALLELBUILDING'}/bin/script/perl-version.pl`;
    }
    die "PERL_VERSION not set\n" unless defined $ENV{'PERL_VERSION'};
    # Crypt::Blowfish_PP module
    unshift (@INC, $ENV{'GEXTPARALLELBUILDING'} . '/' . $ENV{'GSDLOS'} . '/lib/perl/' . $ENV{'PERL_VERSION'});
  }
}

use Crypt::Blowfish_PP;
use Kea;
use Lingua::EN::Syllable;

our $cpu_load_list = [ { 'name' => "none",
                         'desc' => "Almost no processing - all dependent on IO" },
                       { 'name' => "low",
                         'desc' => "A little processing - building lexicon" },
                       { 'name' => "medium",
                         'desc' => "Some processing..." },
                       { 'name' => "high",
                         'desc' => "Data mining and part of speech tagging" }
                     ];

my $arguments = [ { 'name' => "process_exp",
                    'desc' => "{BasePlugin.process_exp}",
                    'type' => "regexp",
                    'deft' => &get_default_process_exp(),
                    'reqd' => "no" },
                  { 'name' => "cpu_load",
                    'desc' => "",
                    'type' => "enum",
                    'deft' => "auto",
                    'list' => $cpu_load_list,
                    'reqd' => "no" },
                  { 'name' => 'debug',
                    'desc' => '',
                    'type' => 'flag',
                    'reqd' => 'no',
                    'deft' => '0',
                    'hiddengli' => 'no'}
                ];

my $options = { 'name'     => "CPULoadTextPlugin",
		'desc'     => "TextPlugin allowing for configurable amounts of CPU load",
		'abstract' => "no",
		'inherits' => "yes",
		'srcreplaceable' => "yes", # Source docs in regular txt format can be replaced with GS-generated html
		'args'     => $arguments };


sub get_default_process_exp
{
  my $self = shift (@_);
  return q^(?i)\.te?xt$^;
}

sub new
{
  my ($class) = shift (@_);
  my ($pluginlist,$inputargs,$hashArgOptLists) = @_;
  push(@$pluginlist, $class);

  push(@{$hashArgOptLists->{"ArgList"}},@{$arguments});
  push(@{$hashArgOptLists->{"OptList"}},$options);

  my $self = new TextPlugin($pluginlist, $inputargs, $hashArgOptLists);

  return bless $self, $class;
}

# do plugin specific processing of doc_obj
sub process
{
  my $self = shift (@_);
  my ($textref, $pluginfo, $base_dir, $file, $metadata, $doc_obj, $gli) = @_;
  my $outhandle = $self->{'outhandle'};

  my $cursection = $doc_obj->get_top_section();

  # get title metadata
  # (don't need to get title if it has been passed
  # in from another plugin)
  if (!defined $metadata->{'Title'})
  {
    my $title = $self->get_title_metadata($textref);
    $doc_obj->add_utf8_metadata ($cursection, "Title", $title);
  }
  # Add FileFormat metadata
  $doc_obj->add_metadata($cursection, "FileFormat", "Text");

  if ($self->{'cpu_load'} =~ /^(medium|high)$/ )
  {
    $self->generateLexicon($doc_obj, $$textref);
    $self->generateWordLengths($doc_obj, $$textref);
    $self->{'first'} = '80,256,1024';
    $self->generateSummaries($doc_obj, $textref);
    $self->{'first'} = undef;
    $self->generateComplexity($doc_obj, $textref);
    $self->generateEncryptedText($doc_obj, $textref, 'thePassword');
  }
  if ($self->{'cpu_load'} eq 'high')
  {
    $self->generateKeywords($doc_obj, $$textref);
  }

  # insert preformat tags and add text to document object
  $self->text_to_html($textref); # modifies the text
  $doc_obj->add_utf8_text($cursection, $$textref);

  return 1;
}


## @function
#
sub _debugPrint
{
  my $self = shift(@_);
  if ($self->{'debug'})
  {
    my ($msg) = @_;
    print '[DEBUG] ' . $msg . "\n";
  }
}
## _debugPrint() ##


## Functions to hopefully create some CPU load ##


## @function
#
sub generateComplexity
{
  my $self = shift(@_);
  my ($doc_obj, $textref) = @_;
  my $text =  $$textref;

  # No of words (we start with 0.1 to prevent things being divided by zero)
  my @words = split(/[^a-zA-Z0-9]+/, $text);
  my $number_of_words = scalar(@words);

  # No of long words, where long is 6 or more characters
  my $number_of_long_words = 0;
  while ($text =~ /\w{6,}/g)
  {
    $number_of_long_words++;
  }

  # No of syllables
  my $number_of_syllables = 0;
  foreach my $the_word (@words)
  {
    $number_of_syllables += syllable($the_word);
  }

  # no of sentences (looking for full stops...)
  my $number_of_sentences = ($text =~ tr/\.//);

  $self->_debugPrint('Number of words: ' . $number_of_words);
  $self->_debugPrint('Number of sentences: ' . $number_of_sentences);
  $self->_debugPrint('Number of syllables: ' . $number_of_syllables);

  # Commetrics Approach
  # A. Big Word Ratio
  #  = Total # of words / Total # of words with > 6 characters
  # B. Word Count Score
  #  = Total # of words / Total # of sentences
  # Score = A / B
  my $commetrics_complexity_score = ($number_of_words / $number_of_long_words) / ($number_of_words / $number_of_sentences);
  $self->_debugPrint('ComMetrics Complexity Score: ' . $commetrics_complexity_score);

  $doc_obj->add_metadata($doc_obj->get_top_section(), 'CommetricsScore', $commetrics_complexity_score);

  # Flesch Reading Ease:
  # Calculate the average number of words you use per sentence.
  # Calculate the average number of syllables per word.
  # Multiply the average number of syllables per word multiplied by 84.6 and subtract it from the average number of words multiplied by 1.015.
  # Subtract the result from 206.835.
  # Algorithm: 206.835 - (1.015 * average_words_sentence) - (84.6 * average_syllables_word)
  my $words_per_sentence = $number_of_words / $number_of_sentences;
  my $syllables_per_word = $number_of_syllables / $number_of_words;
  my $flesch_complexity_score = 206.835 - ($words_per_sentence * 1.015) - ($syllables_per_word * 84.6);
  $self->_debugPrint('Flesch-Kincaid Complexity Score: ' . $flesch_complexity_score);
  $doc_obj->add_metadata($doc_obj->get_top_section(), 'FleschKincaidScore', $flesch_complexity_score);
  my $flesch_grade = 0.38 * $words_per_sentence + 11.8 * $syllables_per_word - 15.59;
  $self->_debugPrint('Flesch-Kincaid Grade: ' . $flesch_grade);
  $doc_obj->add_metadata($doc_obj->get_top_section(), 'FleschKincaidGrade', $flesch_grade);
}
## generateComplexity() ##


## @function
#
sub generateEncryptedText
{
  my $self = shift (@_);
  my ($doc_obj, $textref) = @_;

  my $key_length = 25;
  my $multiplier = 40;

  # Split the string into chunks
  my $text = $$textref;
  # - ensure the length of the text is some multiple of chunk length
  while ((length($text) % ($multiplier * $key_length)) > 0)
  {
    $text .= '#';
  }
  # - now split the text into $multiplier x $key_length bytes chunks
  #   the first key_length bytes is used as the key to encrypt the whole chunk
  my $counter = 0;
  while (length($text) > 0)
  {
    my $key = substr($text, 0, $key_length);
    my $value = $key . substr($text, $key_length, $key_length * ($multiplier - 1));
    my $blowfish = new Crypt::Blowfish_PP($key);
    my $encrypted_text = $blowfish->encrypt($value);
    if ($self->{'cpu_load'} ne 'high')
    {
      $doc_obj->add_utf8_metadata($doc_obj->get_top_section(), sprintf("Encrypted%05d", $counter), $encrypted_text);
    }
    # - shorten text by chunk length bytes, and repeat until text is exhausted
    $text = substr($text, $multiplier * $key_length);
    $counter++;
  }
  $self->_debugPrint('Encrypted ' . $counter . ' x ' . ($multiplier * $key_length) . ' byte chunks');
}
## generateEncryptedText() ##


## @function
#
sub generateKeywords
{
  my $self = shift (@_);
  my ($doc_obj, $text) = @_;
  my $key_phrases = Kea::extract_KeyPhrases('3.0', $text, 'n10');
  $doc_obj->add_utf8_metadata($doc_obj->get_top_section(), 'Keywords', $key_phrases);
  $self->_debugPrint('Generated keywords: "' . $key_phrases . '"');
}
## generateKeywords() ##


## @function
#
sub generateLexicon
{
  my $self = shift (@_);
  my ($doc_obj, $text) = @_;
  my $raw_lexicon = {};
  my @words = split(/[\,\.\s]+/, $text);
  foreach my $word (@words)
  {
    $word = lc($word);
    if (defined $raw_lexicon->{$word})
    {
      $raw_lexicon->{$word}++;
    }
    else
    {
      $raw_lexicon->{$word} = 1;
    }
  }
  my @lexicon;
  foreach my $word (sort keys %{$raw_lexicon})
  {
    push(@lexicon, $word . ':' . $raw_lexicon->{$word});
  }
  if ($self->{'cpu_load'} ne 'high')
  {
    $doc_obj->add_metadata($doc_obj->get_top_section(), "Lexicon", join(', ', @lexicon));
  }
  $self->_debugPrint('Generated lexicon');
}
## generateLexicon() ##


## @function
# extract the first NNN characters as metadata
sub generateSummaries
{
  my $self = shift (@_);
  my ($doc_obj, $textref) = @_;

  foreach my $size (split /,/, $self->{'first'})
  {
    my $tmptext =  $$textref;
    $tmptext =~ s/^\s+//;
    $tmptext =~ s/\s+$//;
    $tmptext =~ s/\s+/ /gs;
    $tmptext = substr ($tmptext, 0, $size);
    $tmptext =~ s/\s\S*$/&#8230;/;
    $doc_obj->add_utf8_metadata ($doc_obj->get_top_section(), 'First' . $size, $tmptext);
    $self->_debugPrint('Generated summary of ' . $size . ' characters');
  }
}


## @function
#
sub generateWordLengths
{
  my $self = shift (@_);
  my ($doc_obj, $text) = @_;
  my $raw_word_lengths = {};
  my @words = split('/[\,\.\s]+/', $text);
  foreach my $word (@words)
  {
    $word = lc($word);
    my $length = length($word);
    if (defined $raw_word_lengths->{$length})
    {
      $raw_word_lengths->{$length} = 1;
    }
    else
    {
      $raw_word_lengths->{$length}++;
    }
  }
  my @word_lengths;
  foreach my $word_length (sort keys %{$raw_word_lengths})
  {
    push(@word_lengths, $word_length . ':' . $raw_word_lengths->{$word_length});
  }
  if ($self->{'cpu_load'} ne 'high')
  {
    $doc_obj->add_metadata($doc_obj->get_top_section(), "WordLengths", join(', ', @word_lengths));
  }
  $self->_debugPrint('Generated word length information');
}
## generateWordLengths() ##


1;
