<?php
class AddonLoader
{
  private $addonPath;
  /**
   * @var Addon[] $addons
   */
  public static $addons;

  public function __construct($addonPath)
  {
    $this->addonPath = $addonPath;
  }

  public function loadAddons()
  {
    if (!is_dir($this->addonPath)) {
      throw new Exception("지정한 폴더가 디렉토리가 아닙니다.: " . $this->addonPath);
    }

    $addonDirs = glob("{$this->addonPath}/*", GLOB_ONLYDIR);

    foreach ($addonDirs as $addonDir) {
      $addonName = basename($addonDir);
      $addonFile = $addonDir . '/' . $addonName . '.addon.php';

      if (file_exists($addonFile)) {
        require_once $addonFile;

        $className = $this->getAddonClassName($addonName);
        if (class_exists($className)) {
          $addon = new $className();
          $addon->className = $className;
          $addon->addonFile = $addonFile;
          $addon->addonPath = $addonDir;
          $addon->init();
          
          self::$addons[$className] = $addon;
        }
      }
    }
  }

  private function getAddonClassName($addonName)
  {
    return str_replace(' ', '', ucwords(str_replace('_', ' ', $addonName))) . 'Addon';
  }
}
