<?php

use EesyPHP\Check;
use EesyPHP\Cli;
use EesyPHP\Date;
use EesyPHP\Log;

use function EesyPHP\___;

/*
 *************************************************************************************************
 *                /!\ Code after this message will only be execute on CLI context /!\
 *************************************************************************************************
 */
if (php_sapi_name() != "cli")
  return true;


/**
 * CLI Helpers
 **/

function print_item_info($item) {
  printf(_("Item #%s:\n"), $item['id']);
  printf("\t"._("ID: %s")."\n", $item['id']);
  printf("\t"._("Name: '%s'")."\n", $item['name']);
  printf("\t"._("Date: %s")."\n", Date :: format($item['date']));
  printf(
    "\t"._("Description: %s")."\n",
    ($item['description']?"'".$item['description']."'":_("Not set"))
  );
  printf("\t"._("Status: %s")."\n", $item['status']);
  return true;
}


/**
 * Common CLI commands
 **/

$orderbys = array('id', 'name', 'date', 'status', 'description');
function cli_list($command_args) {
  global $orderbys;
  $params = array(
    'order' => $orderbys[0],
    'order_direction' => 'ASC',
    'all' => true,
  );
  $patterns = array();
  for($i=0; $i < count($command_args); $i++) {
    switch($command_args[$i]) {
      case '-o':
      case '--orderby':
        $i++;
        if(!in_array($command_args[$i], $orderbys))
          Cli :: usage('Invalid --orderby clause');
        $params['order'] = $command_args[$i];
        break;
      case '-r':
      case '--reverse':
        $params['order_direction'] = 'DESC';
        break;
      case '-s':
      case '--status':
        $i++;
        if(!check_status($command_args[$i]))
          Cli :: usage('Invalid -s/--status clause');
        $params['status'] = $command_args[$i];
        break;
      default:
        $patterns[] = $command_args[$i];
    }
  }

  if (!empty($patterns))
    $params['pattern'] = implode(' ', $patterns);

  $items = search_items($params);
  if (!is_array($items)) {
    Log :: error("Invalid DB info return.\n");
    return False;
  }

  if ($items['count'] == 0){
    echo _("No item.\n");
    return True;
  }

  $tbl = new Console_Table();
  $tbl->setHeaders(
    array(
      'ID',
      'Name',
      'Date',
      'Status',
      'Description',
    )
  );
  foreach($items['items'] as $info) {
    $tbl->addRow(
      array(
        $info['id'],
        $info['name'],
        Date :: format($info['date']),
        $info['status'],
        ($info['description']?$info['description']:''),
      )
    );
  }
  echo $tbl->getTable();
  echo "\n".sprintf(_("%d item(s)"), $items['count'])."\n";
  return True;
}
Cli :: add_command(
  'list',
  'cli_list',
  ___("List/search items"),
  ___("[patterns]"),
  array(
    ___("-o|--orderby       Ordering list criterion. Possible values:"),
    "                     - ".implode("\n                     - ", $orderbys),
    ___("-r|--reverse       Reverse order"),
    ___("-s|--status        Filter on status. Possible values:"),
    "                     - ".implode("\n                     - ", array_keys($status_list)),
  )
);

function cli_show($command_args) {
  if (count($command_args) != 1 || !Check :: id($command_args[0]))
    Cli :: usage(_('You must provide a valid ID.'));

  $item_id = $command_args[0];
  $item = get_item($item_id);

  if (!$item)
    Log :: fatal(_("Item #%s not found."), $item_id);

  print_item_info($item);
  return True;
}
Cli :: add_command(
  'show',
  'cli_show',
  ___("Show item"),
  ___("[ID]")
);

function cli_delete($command_args) {
  if (count($command_args) != 1)
    Cli :: usage(_('You must provide item ID.'));

  // Check URI
  if (!Check :: id($command_args[0]))
    Log :: fatal(_("Invalid item ID"));

  // Check exist
  $item_id = $command_args[0];
  $item = get_item($item_id);
  if (!$item)
    Log :: fatal(_("Item #%s not found."), $item_id);

  print_item_info($item);

  // Sure ?
  echo _("Are you sure you want to delete this item?  Type 'yes' to continue: ");
  $handle = fopen ("php://stdin","r");
  $line = fgets($handle);
  if(trim($line) != 'yes'){
    Log :: warning(_("User cancel"));
    exit;
  }
  echo "\n";

  if (!delete_item($item['id']))
    Log :: fatal(_("An error occured deleting item #%d."), $item_id);

  return True;
}
Cli :: add_command(
  'delete',
  'cli_delete',
  ___("Delete item"),
  ___("[item ID]")
);

function cli_export($command_args) {
  $fd = fopen((count($command_args) >= 1?$command_args[0]:'php://output'), 'w');
  export_items($fd);
  fclose($fd);
  Log :: info("Items export to '".(count($command_args) >= 1?$command_args[0]:'STDOUT')."'.");
}
Cli :: add_command(
  'export',
  'cli_export',
  ___("Export items (as CSV)"),
  ___("[output file path]")
);

function cli_restore($command_args) {
  $fd = fopen((count($command_args) >= 1?$command_args[0]:'php://stdin'), 'r');
  restore_items($fd);
  fclose($fd);
  Log :: info(
    "Items restored from '%s'",
    (count($command_args) >= 1?$command_args[0]:'STDIN')
  );
}
Cli :: add_command(
  'restore',
  'cli_restore',
  ___("Restore items (from CSV)"),
  ___("[input file path]")
);

function cli_cron($command_args) {
  global $item_max_age;
  if (!isset($item_max_age))
    $item_max_age = 30;

  $just_try = false;
  for($i=0; $i < count($command_args); $i++) {
    switch($command_args[$i]) {
      case '-m':
      case '--max-age':
        $i++;
        if(!Check :: id($command_args[$i]))
          Cli :: usage('Invalid -m|--max-age clause');
        $item_max_age = $command_args[$i];
        break;
      case '-j':
      case '--just-try':
        $just_try = true;
        break;
      default:
        Cli :: usage('Invalid parameter '.$command_args[$i]);
    }
  }

  if (!is_int($item_max_age) || $item_max_age <= 0)
    Log :: fatal(
      'Invalid $item_max_age value set in configuration: it\'s must be a positive integer.');
  Log :: debug("cli_cron(): item max age = $item_max_age day(s)");

  $limit = time() - ($item_max_age * 86400);
  Log :: debug("Handle items expiration with creation date limit ".Date :: format($limit).".");

  $items = search_items(array('all' => true));
  $error = false;
  foreach($items['items'] as $item) {
    if ($item['date'] < $limit) {
      if ($just_try) {
        Log :: debug('Just-try mode: do not really delete item #%s (%s, creation date: %s)',
          $item['id'], $item['name'], Date :: format($item['date'])
        );
      }
      else if (delete_item($item['id'])) {
        Log :: info('Item #%s (%s) deleted (creation date: %s)',
          $item['id'], $item['name'], Date :: format($item['date'])
        );
      }
      else {
        Log :: error('Fail to delete item "%s" (%s, creation date: %s)',
          $item['id'], $item['name'], Date :: format($item['date'])
        );
        $error = true;
      }
    }
    else {
      Log :: debug('Item "%s" (%s) still valid (creation date: %s)',
        $item['id'], $item['name'], Date :: format($item['date'])
      );
    }
  }
  return !$error;
}
Cli :: add_command(
  'cron',
  'cli_cron',
  ___("Cron to handle item expiration"),
  null,
  array (
    ___("-j/--just-try    Just-try mode : do not really removed expired item(s)"),
    ___("-m/--max-age     Item expiration limit (in days, optional)"),
  )
);

# vim: tabstop=2 shiftwidth=2 softtabstop=2 expandtab
