<?php
/**
 * @copyright (c) Kufer Software GmbH, Loisachstrasse 4, D-84453 Mühldorf
 */

namespace Kufer\Web\Classes;

class KwResourceLocator
{
  public const INDICATOR_PATH = BASEDIR . '../kw-settings.php';

  private $kwSettings;

  private const PATH_MAP = array(
    'webtools/config' => 'core/',
    'webbasys/layout' => 'kuferweb/layout/',
    'webbasys/layout/settings' => 'kuferweb/layout/settings/',
    'webbasys/layout/sichten' => 'kuferweb/layout/sichten/',
    'classes/userconstants.php' => 'core/userconstants.php'
  );

  private function __construct()
  {
  }

  public static function getInstance(): self
  {
    static $instance = null;
    if (is_null($instance)) {
      $instance = new self();
      $instance->init();
    }

    return $instance;
  }

  public function init(): void
  {
    if (self::fileExists()) {
      include_once self::INDICATOR_PATH;
      if (isset($kw_settings)) {
        $this->kwSettings = $kw_settings;
      }
    }
  }

  public static function fileExists(): bool
  {
    return file_exists(self::INDICATOR_PATH);
  }

  public function locate(string $relativePathToFile, ?string $fallback = null): ?string
  {
    $pathFromSettings = $this->getKwSetting('kw-resources-path');
    if (is_null($pathFromSettings)) {
      return $fallback;
    }

    return $pathFromSettings . $this->resolveMapping($relativePathToFile);
  }

  private function getKwSetting(string $settingsName): ?string
  {
    if (!isset($this->kwSettings[$settingsName])) {
      return null;
    }
    $relativePath = $this->kwSettings[$settingsName];
    $absolutePath = \StringOperations::makeKuferWebPathAbsolute('..' . DIRECTORY_SEPARATOR . $relativePath);
    if (file_exists($absolutePath)) {
      return \StringOperations::makePathEndWithDirectorySeparator($absolutePath);
    } else {
      return null;
    }
  }

  private function resolveMapping(string $path): string
  {
    $p = str_replace('\\', '/', $path);
    $p = \StringOperations::removeTrailing($p, '/');

    $foundPath = isset(self::PATH_MAP[$p]) ? self::PATH_MAP[$p] : '';

    return str_replace('/', DIRECTORY_SEPARATOR, $foundPath);
  }

  public function locateLayoutDirRelative(): string
  {
    if (!self::fileExists()) {
      
      
      return 'layout/';
    }
    
    
    
    return '../../kw-resources/kuferweb/layout/';
  }
}