<?php
$anchorId = 0;

function doAnchor($anchorId, $isLast = false)
{
  $prevAnchor = $anchorId - 1;
  $nextAnchor = $anchorId + 1;
  echo ("<span id=\"change_$anchorId\">");
  if ($prevAnchor >= 0)
    echo (" <a href=\"#change_$prevAnchor\" title=\"#CHANGE $prevAnchor\">PREV</a> ");
  echo (" #CHANGE $anchorId ");
  if ($nextAnchor >= 0 && ! $isLast)
    echo (" <a href=\"#change_$nextAnchor\" title=\"#CHANGE $nextAnchor\">NEXT</a> ");
  echo ("</span>");
}

$newValues = array ();

$strictCompare = array_get ( $_REQUEST, 'strict', "1" ) == "1";
$reset = array_get ( $_REQUEST, 'reset', false ) == "1";

$newConfig_key = array_get ( $_REQUEST, 'newConfig_key', null );
$newConfig_value = array_get ( $_REQUEST, 'newConfig_value', null );

$path = pathCombine ( app ()->basePath, 'config' );
$file = "runtime.php";
$filename = pathCombine ( $path, $file );

if ($reset)
{
  if (fileExists ( $filename ))
    unlink ( $filename );
  $this->redirectToSelf ( false );
  exit ();
}

$deleted = array ();
foreach ( $_REQUEST as $key => $rawvalue )
{
  $configkeyindex = strpos ( $key, "configkey_" );
  if ($configkeyindex === 0)
  {
    $configkey = substr ( $key, $configkeyindex + strlen ( "configkey_" ) );
    if (isEmpty ( $rawvalue ))
    {
      $deleted [] = $configkey;
    }
    else
    {
      $configvalue = eval ( "return ($rawvalue);" );
      $newValues [$configkey] = $configvalue;
    }
  }
}

$originalLeaves = Environment::getConfigLeaves ( Environment::getInstance ()->getConfigEx ( false, false ), $separator );

$different = array ();
if (! isEmpty ( $newConfig_key ))
{
  $different [$newConfig_key] = eval ( "return ($newConfig_value);" );
}
foreach ( $leaves as $path => $item )
{
  if (array_key_exists ( $path, $newValues ))
  {
    if ((! equals ( $item->value, $newValues [$path], $strictCompare ) && ! array_key_exists ( $path, $runtimeLeaves )) || (! equals ( $item->value, $newValues [$path], $strictCompare ) && array_key_exists ( $path, $runtimeLeaves ) && ! equals ( $item->value, $runtimeLeaves [$path], $strictCompare )))
    {
      $different [$path] = $newValues [$path];
    }
  }
}

if (count ( $different ) > 0 || count ( $deleted ) > 0)
{
  $runtimeConfig = array ();
  
  foreach ( $runtimeLeaves as $diffKey => $diffItem )
  {
    $diffValue = $diffItem->value;
    $keys = explode ( $separator, $diffKey );
    $keys [] = $diffValue;
    $slot = array_build_nested_from_array ( $keys );
    $runtimeConfig = array_merge_ex ( $runtimeConfig, $slot );
  }
  
  foreach ( $different as $diffKey => $diffValue )
  {
    $keys = explode ( $separator, $diffKey );
    $keys [] = $diffValue;
    $slot = array_build_nested_from_array ( $keys );
    $runtimeConfig = array_merge_ex ( $runtimeConfig, $slot );
  }
  
  // var_dump_html($runtimeConfig);
  
  if (fileExists ( $filename ))
    unlink ( $filename );
  file_append_line ( $filename, "<?php return " );
  file_append_line ( $filename, _2str ( $runtimeConfig ) );
  file_append_line ( $filename, ";" );
  
  $this->redirectToSelf ( false );
  exit ();
}

?>
<h1>
  Runtime Configuration <a class="icon-refresh"
    href="<?php echo(url($this->getRoute())); ?>"></a> <a
    class="icon-trash"
    href="<?php echo(url($this->getRoute(),array("reset"=>"1"))); ?>"></a>
  (
  <?php echo(count($runtimeLeaves)); ?>
  )
</h1>
<?php doAnchor(0); $anchorId++; ?>
<div style="font-family: monospace;">
  <form method="post">
    <label for="strict_check">Strict:<input id="strict_check"
      type="checkbox" name="strict" value="1"
      <?php if($strictCompare) echo('checked="checked"'); ?> />
    </label><input type="submit" />
    <table class="table table.condensed">
      <thead>
        <tr>
          <th width="40%">Path</th>
          <th width="10%">Type</th>
          <th width="50%">Value</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td width="40%"><input
            style="font-family: monospace; width: 100%;"
            name="newConfig_key" type="text" value=""></td>
          <td width="10%"></td>
          <td width="50%"><input
            style="font-family: monospace; width: 100%;"
            name="newConfig_value" type="text" value=""></td>
        </tr>
        <?php
        $deleteBoxEnabled = false;
        foreach ( $leaves as $path => $item )
        {
          $itemId = "configKeyItem_" . uniqid (); // "configkey_{$path}";
          $rowstyle = "";
          $originalValueBox = "";
          $deleteValueBox = "";
          $changesAtRuntime = array_key_exists ( $path, $runtimeLeaves );
          if ($changesAtRuntime && ! equals ( $item->value, $originalLeaves [$path]->value, $strictCompare ))
          {
            $rowstyle = " border-color: red;";
            $originalValueBox = "<pre title=\"Original value\">" . _2str ( $originalLeaves [$path]->value ) . "</pre>";
          }
          elseif ($changesAtRuntime)
          {
            $rowstyle = " border-color: orange;";
          }
          
          $anchorCode = "";
          if ($changesAtRuntime)
          {
            if ($deleteBoxEnabled)
              $deleteValueBox = "<font size=\"small\"><a href=\"#$itemId\" onclick=\"$( '#{$itemId}' ).val('');\">[x]</a></font>";
            $anchorCode = ob_do ( doAnchor, $anchorId );
            $anchorId ++;
          }
          
          echo ("<tr>
                <td width=\"40%\">$path</td>
                <td width=\"10%\">" . gettype ( $item->value ) . "</td>
                <td width=\"50%\">
                <input style=\"font-family: monospace; width: 100%;$rowstyle\" name=\"configkey_{$path}\" id=\"configkey_{$path}\" type=\"text\" value=\"" . _2str ( $item->value ) . "\" />
                $originalValueBox $anchorCode $deleteValueBox
                </td>
                </tr>");
        }
        ?>
      </tbody>
    </table>
    <?php doAnchor($anchorId, true); ?>
  </form>
</div>
