<?php
/**
 * @copyright (c) Kufer Software GmbH, Oderstraße 7, D-84453 Mühldorf
 */

namespace Kufer\Web\Classes\Api;

use Kufer\Web\Classes\Addfunctions\Guid;


class WebpageUniqueIdApi
{
  private function __construct()
  {
  }

  
  private static $cache;

  
  public static function id(): Guid
  {
    if (is_null(static::$cache)) {
      static::$cache = static::getFromFile();
      if (is_null(static::$cache)) {
        static::$cache = static::createFile();
        if (is_null(static::$cache)) {
          throw new WebpageUniqueIdCouldNotBeAccessedException(
            "Auf die Datei '" . print_r(static::filePath(), true) . "' kann nicht zugegriffen werden."
          );
        }
      }
    }

    return static::$cache;
  }

  
  private static function filePath(): array
  {
    $filename = 'web-unique-id.key';

    return array_unique(array(
      \FSOperations::path(\ConstantOperations::getPathForCoreSettings(), $filename),
       \FSOperations::path(BASEDIR, 'webtools', 'config', $filename)
    ));
  }

  
  private static function getFromFile(): ?Guid
  {
    foreach (static::filePath() as $filePath) {
      $contents = @file_get_contents($filePath);
      if ($contents !== false) {
        if (Guid::validate($contents)) {
          return new Guid($contents);
        }
      }
    }

    return null;
  }

  private static function createFile(): ?Guid
  {
    foreach (static::filePath() as $filePath) {
      $guid = Guid::generate();

      $fh = @fopen($filePath, 'x');
      if ($fh !== false) {
        fwrite($fh, (string)$guid);
        if (fclose($fh)) {
          return $guid;
        }
      }
    }

    return null;
  }
}