package MHelp;
use strict;

use vars qw(%Categories %Keywords);

use MCoreTools;
use DirHandle;

sub load_help {
  my ($class) = @_;
  
  mudlog "Loading help...";
  %Categories = %Keywords = ();
  
  my $root = $::Config{help_path};
  my $hdir = DirHandle->new(rdir($root)) or do {mudlog "ERROR: Failed to open help file directory: $!"; return};
  foreach my $cname ($hdir->read) {
    next unless $cname !~ /\W/ and -d rdir($root.'/'.$cname);
    #mudlog "Scanning help category $cname";

    my $cat = ($Categories{$cname} ||= {items => {}});
    my $cdir = DirHandle->new(rdir($root.'/'.$cname)) or do {mudlog "ERROR: Failed to open help file category '$cname': $!"; return};

    foreach my $fname ($cdir->read) {
      next unless (my $hname = $fname) =~ s/\.help$//;
      #mudlog "Reading help file $cname/$fname";
      
      my $fh = IO::File->new(rfile($root.'/'.$cname.'/'.$fname)) or do {mudlog "ERROR: Failed to open help file '$cname/$fname': $!"; return};
      my @keywords = split /\s*,\s*/, <$fh>;
      my $text = do {local $/; <$fh>};
      $fh->close;
      
      $cat->{items}->{$hname} = {
        text => $text,
        keywords => [@keywords],
      };
      foreach (@keywords, $hname) {
        $cat->{keywords}->{$_} = $hname;
        $Keywords{$_} = [$cname, $hname];
      }
      
    } # end category dir
  } # end help dir
} # end load_help

sub search {
  my ($class, $keyword, $caller) = @_;
  
  my (%hseen, %cseen, %sseen);
  return (grep !$hseen{$$_[0]}++, map $Keywords{$_}, grep /\Q$keyword/, keys %Keywords), (
    map(['command', $_], grep /\Q$keyword/ && !$cseen{$_}++, $caller->commands_for_display),
    map(['social', $_], grep /\Q$keyword/ && !$sseen{$_}++, MSocials->all),
  );
}

sub hf_text {
  my ($class, $cat, $name, $caller) = @_;
  
  $cat = lc $cat;
  if ($cat eq 'command' and $caller->cmdi_exists($name)) {
    my $buf = "&:c;- Command '$name'&:n;\n";
    my $aka = join ', ', $caller->cmdi_aliases($name);
    $buf .= "&:c;Also known as: $aka&:n;\n" if $aka;
    if ($caller->priv_watcher) {
      $buf .= "&:c;Requires: " . (join ', ', $caller->cmdi_requires($name)) . "&:n;\n";
    }      
    $buf .= $caller->cmdi_help($name) || 'No help is available for this command.';
    return $buf;
  } elsif ($cat eq 'social') {
    my $msg = MSocials->info_msg($name) or die "CFAIL:There is no such social.";
    my @advs = MSocials->info_advs($name);
    $msg =~ s/<target>/&lt;target&gt;/;
    return "&:c;- Social '$name'&:n;\nMessage: " . ucfirst $caller->desc_gen($msg,self=>$caller)
      . "\nAvailable adverbs: @advs\n";
  } else {
    return $Categories{$cat}{items}{$name}{text};
  }
}

1;