package Hexed::Prompt;

use strict;
use warnings;
use include;

use Cursed::Window;
our @ISA = ("Cursed::Window");

use Curses;

# Create and return a new prompt window.
sub spawn {
  my $self = shift;
  $self->ui->install_keymap($self, $self->ui->input_handler);
}

# Go through the entire prompting process
sub prompt {
  my ($self, $query, $limit) = @_;
  # TODO: messy debugging, handling, testing
  croak "prompt query is too long!" if length($query) > $self->{Width};
  croak "prompt limit is too long!" if $limit > $self->{Width};

  # TODO: messy... all of it! a pattern? Fixed's job somehow?
  # Set the prompt title.
  $self->{Win}->standend;
  $self->{Win}->attron(A_REVERSE);
  # Center the query.
  my $x = center($query, $self->{Width});
  $self->{Win}->addstr($self->{Y1}, $self->{X1} + $x, $query);
  $self->draw;

  # Turn the cursor on and start the magic loop, maaan.
  $x = 0;
  $self->{Win}->standend;
  curs_set(1);
  $self->{Win}->move($self->{Y1} + 1, $self->{X1} + $x);
  $self->draw;
  my @in;
  until ((my $key = $self->ui->wait_input) eq "<^M>") {
    if ($key eq "<KEY_LEFT>") {
      $x-- unless $x == 0;
    } elsif ($key eq "<KEY_RIGHT>") {
      $x++ unless $x == @in;  # We can move one past the next character
    } elsif ($key eq "<KEY_HOME>") {
      $x = 0;
    } elsif ($key eq "<KEY_END>") {
      $x = @in;
    } elsif ($key eq "<KEY_BACKSPACE>") {
      next if $x == 0;
      splice @in, $x - 1, 1;
      $x--;
      $self->{Win}->move($self->{Y1} + 1, $self->{X1} + $x);
      $self->{Win}->clrtoeol;
      # A full redraw is quite unnecessary
      $self->{Win}->box(0, 0) if $self->{Border};
    } elsif ($key eq "<KEY_DC>") {
      next if $x == @in;
      splice @in, $x, 1;
      $self->{Win}->clrtoeol;
      $self->{Win}->box(0, 0) if $self->{Border};
    } elsif ($key =~ m/<.+>/) {
    } else {
      next if $x == $limit;
      splice @in, $x, 0, $key;
      $x++;
    }
    $self->{Win}->addstr($self->{Y1} + 1, $self->{X1}, join("", @in));
    $self->{Win}->move($self->{Y1} + 1, $self->{X1} + $x);
    $self->draw;
  }
  # And... done!
  curs_set(0);
  return join "", @in;
}

42;
