<?php
namespace nur\b\proc;

use nur\A;
use nur\shell;

/**
 * Class AbstractCmdList: une séquence de commandes séparées par ;, && ou ||
 */
abstract class AbstractCmdList extends AbstractCmd {
  /** @var string|null */
  protected $sep;

  function __construct(?string $sep, $cmd=null, ?string $input=null, ?string $output=null) {
    parent::__construct();
    $this->sep = $sep;
    $this->add($cmd, $input, $output);
  }

  function addLiteral($cmd): self {
    A::append_nn($this->cmds, $cmd);
    return $this;
  }

  function add($cmd, ?string $input=null, ?string $output=null): self {
    if ($cmd !== null) {
      if (!($cmd instanceof ICmd)) {
        shell::fix_cmd($cmd, null, $input, $output);
      }
      $this->cmds[] = $cmd;
    }
    return $this;
  }

  function getCmd(?string $sep=null): string {
    if ($sep === null) $sep = "\n";

    $actualCmd = [];
    A::append_nn($actualCmd, $this->getVars($sep));

    $parts = [];
    foreach ($this->cmds as $cmd) {
      if ($cmd instanceof ICmd) {
        $cmd = "(".$cmd->getCmd($sep).")";
      }
      $parts[] = $cmd;
    }
    $psep = $this->sep;
    if ($psep === null) $psep = $sep;
    A::append($actualCmd, implode($psep, $parts));

    return implode($sep, $actualCmd);
  }
}