<?php

//
function aws_s3_testPage() {
  
  echo plugin_header('AWS S3 > Run Tests');
  
  // check for errors (i.e. in auth info or bucket name)
  _aws_s3_init(); // this will throw errors if we can't authenticate
  
  ?>
  <hr>
  <h3>Test Actions:</h3>
  <a href="?_pluginAction=aws_s3_testPage">List objects</a><br>
  <a href="?_pluginAction=aws_s3_testPage&amp;maxKeys=2">List objects (maxKeys = 2)</a><br>
  <a href="?_pluginAction=aws_s3_testPage&amp;prefix=testing/5">List objects (prefix = testing/5)</a><br>
  <a href="?_pluginAction=aws_s3_testPage&amp;doBasicTests=1">Run basic tests (including putting 1 image)</a><br>
  <a href="?_pluginAction=_aws_s3_putBulkTesting" onclick="return confirm('Are you sure?');">Put 1000 tiny objects</a><br>
  <a href="?_pluginAction=_aws_s3_deleteAllTestingObjects" onclick="return confirm('Are you sure?');">Delete all testing/ objects</a><br>
  <hr>
  <?php
  
  if (@$_REQUEST['doBasicTests']) {
    aws_s3_testPage_doBasicTests();
  }
  else {
    aws_s3_testPage_list(@$_REQUEST['prefix'], @$_REQUEST['pageKey'], @$_REQUEST['maxKeys']);
  }
  
  echo plugin_footer();
}

//
function aws_s3_testPage_doBasicTests() {
  // check if 'hello' exists
  showme("Does testing/hello exist? " . (aws_s3_exists('testing/hello') ? 'yes' : 'no'));
  
  // put a small html file
  $objectUrl = aws_s3_put('testing/hello', 'text/html', 'Hello world!');
  echo 'Uploaded (i.e. put) file: <a target="_blank" href="' . htmlencode($objectUrl) . '">' . htmlencode($objectUrl) . '</a><br>';
  
  // check if 'hello' exists
  showme("Does testing/hello exist? " . (aws_s3_exists('testing/hello') ? 'yes' : 'no'));
  
  // delete a specific key
  aws_s3_delete('testing/hello');
  showme("Deleted testing/hello");

  // check if 'hello' exists
  showme("Does testing/hello exist? " . (aws_s3_exists('testing/hello') ? 'yes' : 'no'));

  // put an image
  $samplePngFileData = base64_decode("iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAIAAAACUFjqAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAadEVYdFNvZnR3YXJlAFBhaW50Lk5FVCB2My41LjEwMPRyoQAAAINJREFUKFNlj8ENABEQRYdOxE3iqAYnfUg4KkoXGtCPo/12JLtr30HMPPMzaP6otQohvPe4n3qMAUdEOFGe2loLB1prKJcupdzqGQ0hcIeUUqjRhTPG8J0doBjjyiKSUvKoc25LDs858wsGMezAXi2lxO6dDJ7NtdZwvfdd35wf+zDnBU4pxemXbtimAAAAAElFTkSuQmCC");
  $objectUrl = aws_s3_put('testing/' . uniqid('', true), 'image/png', $samplePngFileData);
  echo 'Uploaded (i.e. put) file: <a target="_blank" href="' . htmlencode($objectUrl) . '">' . htmlencode($objectUrl) . '</a><br>';
  
  echo "<hr>";
  echo "Showing first 1000 keys in alphabetical order...<br>";
  
  aws_s3_testPage_list();
}

//
function aws_s3_testPage_list($prefix = '', $pageKey = '', $maxKeys = 1000) {
  $maxKeys = $maxKeys ?: 1000; // if $maxKeys was '' (because it came from @$_REQUEST['maxKeys']), the default function arg above won't have worked!
  $makeUrl = function($array) use($prefix, $maxKeys) {
    $array = array_merge([
      '_pluginAction' => 'aws_s3_testPage',
      'prefix'        => $prefix,
      'maxKeys'       => $maxKeys,
    ], $array);
    return htmlencode(http_build_query($array));
  };
  
  showme("aws_s3_listPage($prefix, $pageKey, $maxKeys)");
  
  if (@$_REQUEST['delete']) {
    showme("aws_s3_delete(" . @$_REQUEST['delete'] . ")");
    aws_s3_delete(@$_REQUEST['delete']);
  }
  
  list($rows, $nextPageKey) = aws_s3_listPage($prefix, $pageKey, $maxKeys);
  
  ?>
    <?php if ($nextPageKey): ?>
      <a href="?<?php echo $makeUrl(['pageKey'=>$nextPageKey]) ?>">Next Page &gt;&gt;</a>
    <?php else: ?>
      No more results to display!
    <?php endif ?>
    <?php if ($pageKey): ?>
      <a href="?<?php echo $makeUrl([]) ?>">&lt;&lt; First Page</a>
    <?php endif ?>
    
    <table class="data sortable table table-striped">
      <tr><th>Key</th><th>Size</th><th>LastModified</th><th>Action</th></tr>
      <?php foreach ($rows as $row): ?>
        <tr>
          <td><a target="_blank" href="https://s3-<?php echo htmlencode($GLOBALS['AWS_S3_REGION']) ?>.amazonaws.com/<?php echo htmlencode($GLOBALS['AWS_S3_BUCKET']) ?>/<?php echo htmlencode($row['Key']) ?>"><?php echo htmlencode($row['Key']) ?></a></td>
          <td><?php echo htmlencode($row['Size']) ?></td>
          <td><?php echo htmlencode($row['LastModified']->__toString()) ?></td>
          <td><a onclick="return confirm('Are you sure?')" href="?<?php echo $makeUrl(['delete'=>$row['Key']]) ?>">delete</a></td>
        </tr>
      <?php endforeach ?>
    </table>
  <?php
}

//
pluginAction_addHandler('_aws_s3_putBulkTesting', 'admins');
function _aws_s3_putBulkTesting() {
  $uniqueId = uniqid('', true);
  for($i = 0; $i < 1000; $i += 1) {
    aws_s3_put('testing/bulk-' . $uniqueId . '-' . $i, 'text/plain', "$i");
  }
  
  redirectBrowserToUrl('?_pluginAction=aws_s3_testPage');
}

// 
pluginAction_addHandler('_aws_s3_deleteAllTestingObjects', 'admins');
function _aws_s3_deleteAllTestingObjects() {
  foreach (array_chunk(array_pluck(aws_s3_list('testing/'), 'Key'), 1000) as $keys) {
    aws_s3_deleteMultiple($keys);
  }
  
  redirectBrowserToUrl('?_pluginAction=aws_s3_testPage');
}
