<?php

namespace Drupal\nodehive_core\Plugin\DashboardBlock;

use Drupal\content_planner\DashboardBlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a File Space Usage block for Content Planner Dashboard.
 *
 * @DashboardBlock(
 *   id = "nodehive_file_space_usage_block",
 *   name = @Translation("NodeHive File Space Usage Widget"),
 *   category = "NodeHive",
 *   id_category = "nodehive"
 * )
 */
class NodeHiveFileSpaceUsageBlock extends DashboardBlockBase implements ContainerFactoryPluginInterface {
  use StringTranslationTrait;

  /**
   * The file system service.
   *
   * @var \Drupal\Core\File\FileSystemInterface
   */
  protected $fileSystem;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    $instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
    $instance->fileSystem = $container->get('file_system');
    return $instance;
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    // Calculate the disk space usage.
    $publicSpaceUsage = $this->getDirectorySize($this->fileSystem->realpath("public://"));
    $privateSpaceUsage = $this->getDirectorySize($this->fileSystem->realpath("private://"));
    $totalSpaceUsage = $publicSpaceUsage + $privateSpaceUsage;

    // Format sizes to MB.
    $publicSpaceUsageMB = $this->formatSize($publicSpaceUsage);
    $privateSpaceUsageMB = $this->formatSize($privateSpaceUsage);
    $totalSpaceUsageMB = $this->formatSize($totalSpaceUsage);

    // Prepare the render array for the table.
    $build['file_space_usage_table'] = [
      '#type' => 'table',
      '#header' => [['data' => $this->t('Metric')], ['data' => $this->t('Size')]],
      '#rows' => [
              [$this->t('Total Disk Usage'), $totalSpaceUsageMB],
              [$this->t('Public Folder'), $publicSpaceUsageMB],
              [$this->t('Private Folder'), $privateSpaceUsageMB],
      ],
      '#empty' => $this->t('No file space usage information available.'),
      '#attributes' => ['class' => ['file-space-usage-class']],
      '#cache' => [
      // Consider caching the block for 1 hour.
        'max-age' => 3600,
      ],
    ];

    return $build;
  }

  /**
   * Calculates the total size of a directory.
   *
   * @param string $directory
   *   The directory path.
   *
   * @return int
   *   The total size of the directory in bytes.
   */
  protected function getDirectorySize($directory) {
    $size = 0;
    foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($directory)) as $file) {
      if ($file->isFile()) {
        $size += $file->getSize();
      }
    }
    return $size;
  }

  /**
   * Formats bytes into a more readable format (e.g., MB).
   *
   * @param int $bytes
   *   The size in bytes.
   * @param int $precision
   *   The precision of the rounding.
   *
   * @return string
   *   The formatted size.
   */
  protected function formatSize($bytes, $precision = 2) {
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);
    $bytes /= pow(1024, $pow);

    return round($bytes, $precision) . ' ' . $units[$pow];
  }

}
