<?php
namespace Civi\Setup;

class Template {

  protected $filetype;

  protected $smarty;
  protected $beautifier;

  public function __construct($srcPath, $fileType) {
    $this->filetype = $fileType;

    $this->smarty = \Civi\Setup\SmartyUtil::createSmarty($srcPath);

    $this->assign('generated', "DO NOT EDIT.  Generated by Installer");

    if ($this->filetype === 'php') {
      $packagePath = PackageUtil::getPath($srcPath);
      require_once implode(DIRECTORY_SEPARATOR, [$packagePath, 'PHP', 'Beautifier.php']);
      // create an instance
      $this->beautifier = new PHP_Beautifier();
      $this->beautifier->addFilter('ArrayNested');
      // add one or more filters
      $this->beautifier->setIndentChar(' ');
      $this->beautifier->setIndentNumber(2);
      $this->beautifier->setNewLine("\n");
    }
  }

  public function assign($tpl_var, $value = NULL) {
    return $this->smarty->assign($tpl_var, $value);
  }

  /**
   * Run template generator.
   *
   * @param string $infile
   *   Filename of the template, without a path.
   * @return string
   */
  public function getContent($infile) {
    $contents = $this->smarty->fetch($infile);

    if ($this->filetype === 'php') {
      $this->beautifier->setInputString($contents);
      $this->beautifier->process();
      $contents = $this->beautifier->get();
      // The beautifier isn't as beautiful as one would hope. Here's some extra string fudging.
      $replacements = [
        ') ,' => '),',
        "\n  }\n}\n" => "\n  }\n\n}\n",
        '=> true,' => '=> TRUE,',
        '=> false,' => '=> FALSE,',
      ];
      $contents = str_replace(array_keys($replacements), array_values($replacements), $contents);
      $contents = preg_replace('#(\s*)\\/\\*\\*#', "\n\$1/**", $contents);
      // Convert old array syntax to new square brackets
      $contents = CRM_Core_CodeGen_Util_ArraySyntaxConverter::convert($contents);
    }

    return $contents;
  }

  /**
   * @param array $inputs
   *   Template filenames.
   */
  public function getConcatContent($inputs) {
    $content = '';
    foreach ($inputs as $infile) {
      // FIXME: does not beautify.  Document.
      $content .= $this->smarty->fetch($infile) . "\n";
    }

    return $content;
  }

}
