package MTerminal::Mud;
use strict;
use integer;
use MTerminal::ANSI;
use vars qw(@ISA);
@ISA = qw(MTerminal::ANSI);

use MCoreTools;

my $ANSIMATCH = "(?:\c[\\[[0-9;]*?m)";

sub new {
  my ($class, $con) = @_;
  my $self = bless $class->SUPER::new(), $class;
  return $self;
}

sub init {
  my ($self, $con) = @_;
  $self->SUPER::init($con);
  $con->send_str("\n\nMarn3\njilgox\n"); # FIXME: hardcoded name/pass
  $con->cmd_execute(undef, 'attach', ''); # FIXME: shouldn't know about interpreter here
}

sub output {
  my ($self, $con, $sx) = @_;
  
  my $result = MTerminal::ANSI::_sx2ansi($con, $sx, {
    userstyle => $con->pref('ansi_style'),
    max_width => ($con->pref('scr_width') || 80) - 12,
  }, "\c[[0m");

  return if $result =~ /$ANSIMATCH*\[gateway\]/;
  1 while $result =~ s/[\r\n ]+($ANSIMATCH*)\Z/$1/;
  return unless length $result;
  
  my @reslines = split /\n/, $result;
  my $prevcode = "\c[[0m";
  for (@reslines) {
    $_ = $prevcode . $_;
    /.*($ANSIMATCH)/ and $prevcode = $1;
  }    

  $result = join "\n", @reslines;
  $result =~ s/$ANSIMATCH//g if $con->pref('no_ansi');
  $result =~ s/^/echo [gateway] /gm;

  $con->send_str($result . "\n");
  $con->needs_flush;
}

sub input {
  my ($self, $con, $input) = @_;
  #$input =~ s/$ANSIMATCH//g;
  return '' if $input =~ /^$ANSIMATCH*(<rep>You echo ')?\[gateway]/;
  $con->object->sact([action=>{}, '[gateway] ', [user=>{}, ['ipre'=>{}, $input]]]);
  return '';
}

sub send_prompt {
  my ($self) = @_;
  $self->{prompt_event} = undef;
  $self->{prompt_event_time} = undef;
  $self->{next_prompt} = undef;
}

sub dispose {$_[1]->send_str("quit gateway disconnect\n")}

1;
