#!perl6

use Sparrow6::Task::Repository;
use Sparrow6::Task;

sub MAIN (
  $thing?, 
  Bool :$debug            = False, 
  Bool :$clean            = False, 
  Bool :$help             = False, 
  Bool :$index-update     = False, 
  Bool :$list             = False, 
  Bool :$search           = False, 
  Bool :$upload           = False, 
  Bool :$repo-init        = False, 
  Bool :$install          = False, 
  Bool :$plg-run          = False, 
  Bool :$plg-man          = False, 
  Bool :$task-run         = False, 
  Bool :$task-set         = False, 
  Bool :$task-cat         = False, 
  Bool :$task-list        = False, 
  Bool :$task-del         = False, 
  Bool :$module-run       = False, 
  Bool :$force            = False, 
  Str  :$prefix, 
)

{

  my $repo-api = Sparrow6::Task::Repository::Api.new(
    debug   => $debug,
    prefix  => $prefix
  );

  my $task-cli = Sparrow6::Task::Cli.new(
    debug   => $debug,
    prefix  => $prefix
  );

  if ($help) {
    $task-cli.help;
    exit;
  } 

  if $repo-init {

    $repo-api.console("repo initialization");
    $repo-api.repo-init($thing);

  } elsif $upload {

    $repo-api.console("upload plugin");
    $repo-api.plugin-upload();

  } elsif $install && $thing {

    $repo-api.console("install plugin $thing");

    $repo-api.plugin-install($thing, %( force => $force ));

  } elsif $task-run && $thing {

    $task-cli.console("run task $thing");

    $task-cli.task-run($thing);

  } elsif $module-run && $thing {

    $task-cli.console("run module $thing");

    $task-cli.module-run($thing);

  } elsif $plg-run && $thing {

    $task-cli.console("run plg $thing");

    for $thing.split(/ "+" /) -> $i {
      $task-cli.plg-run($i);
    }

  } elsif $plg-man && $thing {

    $repo-api.console("man plg $thing");

    $repo-api.plugin-man($thing);

  } elsif $module-run && $thing {

    $task-cli.console("run module $thing");

  } elsif $task-set && $thing {

    $task-cli.console("set task $thing");

    $task-cli.task-set($thing);

  } elsif $task-cat && $thing {

    $task-cli.console("show task $thing");

    $task-cli.task-cat($thing);

  } elsif $task-del && $thing {

    $task-cli.console("delete task $thing");

    $task-cli.task-del($thing);

  } elsif $task-list {

    $task-cli.console("list tasks");

    $task-cli.task-list;

  } elsif $index-update {

    $repo-api.console("update local index");
    $repo-api.index-update();

  } elsif $list {

    $repo-api.console("installed plugins");

    for $repo-api.installed-plugins() -> $i {
      say "{$i[0]} ... $i[1] ... $i[2]"
    }

  } elsif $search {

    $repo-api.console("search plugins");
    for $repo-api.search-plugins($thing) -> $i {
      if $i[1].defined {
        say "{$i[0]} ... {$i[1]} ... {$i[2]}"
      } else {
        say "{$i[0]} ... Nil ... {$i[2]}"
      }
    }
  } else {

    $task-cli.help();

    exit(10);

  }

}


