<?php

declare(strict_types=1);

namespace Drupal\automated_testing_kit\Drush\Commands;

use Consolidation\OutputFormatters\StructuredData\RowsOfFields;
use Drush\Attributes as CLI;
use Drush\Commands\DrushCommands;

/**
 * Custom Drush commands for Automated Testing Kit.
 */
final class AutomatedTestingKitDrushCommands extends DrushCommands {

  /**
   * Command description here.
   */
  #[CLI\Command(name: 'file:properties', aliases: ['fprop'])]
  #[CLI\Argument(name: 'filepath', description: 'Path to the file.')]
  #[CLI\Usage(name: 'file:properties filepath]', description: 'Usage description.')]
  #[CLI\FieldLabels(labels: [
    'directory' => 'Directory',
    'filename' => 'Filename',
    'filesize' => 'File Size',
    'filectime' => 'File Created',
    'filemtime' => 'File Modified',
    'fileatime' => 'File Accessed',

  ])]
  public function fileProperties($filepath, $options = ['format' => 'json']): RowsOfFields {
    // Get the file properties.
    if (file_exists($filepath)) {
      if (is_dir($filepath)) {
        $basename = '<directory>';
      }
      else {
        $basename = basename($filepath);
      }

      $rows[] = [
        'directory' => dirname($filepath),
        'filename' => $basename,
        'filesize' => filesize($filepath),
        'filectime' => filectime($filepath),
        'filemtime' => filemtime($filepath),
        'fileatime' => filemtime($filepath),
      ];

      return new RowsOfFields($rows);
    }
    $this->logger()->error(dt("Does not exist: $filepath."));
    return new RowsOfFields([]);
  }

  /**
   * Create a non-managed file under sites/default/files.
   *
   * Create a file for the testing purpose, with the given path, name,
   * size and permissions.
   */
  #[CLI\Command(name: 'file:create')]
  #[CLI\Argument(name: 'filepath', description: 'Path and name to the file, relative to the project root.')]
  #[CLI\Option(name: 'size', description: 'File size, in bytes')]
  #[CLI\Option(name: 'permissions', description: 'File permissions in UNIX notation, e.g. 0644')]
  #[CLI\Usage(
    name: 'file:create sites/default/files/test-content/test.txt',
    description: 'Create a file',
  )]
  public function fileCreate($filepath, $options = ['size' => 30, 'permissions' => '0600']) {
    // Create a directory and nested directories if needed.
    $directory = dirname($filepath);
    if (!is_dir($directory) && !mkdir($directory, 0777, TRUE)) {
      throw new \Exception("$directory: access denied");
    }

    // Write file contents.
    $content = 'Ama mama bum banana. ';

    $contentLength = $options['size'];
    while (strlen($content) < $contentLength) {
      $content .= substr($content, 0, $contentLength - strlen($content));
    }

    if (!file_put_contents($filepath, $content)) {
      throw new \Exception("Write failure: $filepath");
    }

    // Set permissions.
    $permissions = $options['permissions'];
    chmod($filepath, intval($permissions, 8));
  }

}
