<?php
declare(strict_types=1);

namespace WP_AUX\Entities\Admin\AuxComponents;

use AuxCF;
use WP_AUX;

class AuxComponentAuditFileEntity
{
  protected string $filePath;
  protected \DateTimeImmutable $date;
  protected ?string $relativePath = null;
  protected ?string $pathLetter = null;
  protected ?string $pathKey = null;
  protected ?AuxComponentAuditFileEntity $parentFile = null;

  public function __construct(string $filePath) {
    $this->filePath = $filePath;
    $this->date = \DateTimeImmutable::createFromFormat('U', (string) filemtime($this->filePath));

    $this->resolvePath();

    if ($this->relativePath) {
      $classPath = strtr(substr($this->relativePath, 0, -4), DIRECTORY_SEPARATOR, '\\');

      if ($reflect = new \ReflectionClass($classPath)) {
        if ($parentClass = $reflect->getParentClass()) {
          $this->parentFile = new AuxComponentAuditFileEntity($parentClass->getFileName());
        }
      }
    }
  }

  protected function resolvePath(): void
  {
    $filePath = $this->filePath;

    $try = [
      '/WP_AUX/' . WP_AUX::FIELDS_DIR . '/' => ['F', 'field'],
      '/WP_AUX/' . WP_AUX::FIELD_GROUPS_DIR . '/' => ['G', 'group'],
      '/WP_AUX/' . WP_AUX::FIELDS_COLLECTIONS_DIR . '/' => ['C', 'collection'],
      '/AuxCF/' . AuxCF::FIELDS_DIR . '/Traits/' => ['T', 'trait'],
      '/AuxCF/' . AuxCF::FIELDS_DIR . '/' => ['B', 'base'],
      '/AuxCF/Entities/' => ['R', 'root'],
    ];

    foreach ($try as $dir => $type) {
      if (substr_count($filePath, $dir)) {
        $this->relativePath = strstr($filePath, $dir);
        $this->pathLetter = $type[0];
        $this->pathKey = $type[1];
        break;
      }
    }
  }

  public function getParentFile(): ?AuxComponentAuditFileEntity
  {
    return $this->parentFile;
  }

  public function getDateString(string $format = 'l, F j, Y @ h:i a'): string
  {
    return $this->date->format($format);
  }

  public function getFilePath(): ?string
  {
    return $this->filePath;
  }

  public function getRelativePath(): ?string
  {
    return $this->relativePath;
  }

  public function getPathLetter(): ?string
  {
    return $this->pathLetter;
  }

  public function getPathKey(): ?string
  {
    return $this->pathKey;
  }
}
