#! /usr/bin/env raku

use Transit::Network;
use Transit::Network::i8n;
use Text::ShellWords;
use Linenoise;

multi sub MAIN (:$lang, :$help)
{
  set-lang($lang) if $lang;

  &(%Transit::Network::commands<help>)() if $help;

  constant HIST_FILE = ( $*HOME.add: '.networkplanner-hist' ).Str;
  constant HIST_LEN  = 25;

  linenoiseHistoryLoad(HIST_FILE);
  linenoiseHistorySetMaxLen(HIST_LEN);

  linenoiseSetCompletionCallback(-> $row, $c
  {
    for @Networkplanner::Helper::commands.grep(/^ $row /).sort -> $cmd
    {
      linenoiseAddCompletion($c, $cmd);
    }
  });

  say "networkplanner: { Transit::Network::i8n::translate("Enter «exit» to exit") }";

  while (my $row = linenoise '> ').defined
  {
    linenoiseHistoryAdd($row);

    my @items   = shell-words $row;
    my $command = @items ?? @items.shift !! "";

    given $command
    {
      when "exit"              { last; }
      when $command eq any(@Transit::Network::commands) { &(%Transit::Network::commands{$command})(@items); }
      default                  { say "{ Transit::Network::i8n::translate("Unknown command") }: \"$_\" (Legal commands: { @Transit::Network::commands })" }
    }
  }

  linenoiseHistorySave(HIST_FILE);
}

multi sub MAIN ($file where $file.IO.f && $file.IO.r, :$lang, :$help)
{
  set-lang($lang) if $lang;

  &(%Transit::Network::commands<help>)() if $help;
  
  my @rows  = get-file($file);
  my $first = @rows.shift;

  return unless Transit::Network::check-first-line-setup($first);

  for @rows -> $row
  {
    next unless $row;

    my @items   = $row.words;
    my $command = @items.shift;

    &(%Transit::Network::commands{$command})(@items) if %Transit::Network::commands{$command};
  }
}
