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


class SettingsFactory
{
  
  private static $instances = array();

  
  public static function getSettings($classname)
  {
    if (!isset(self::$instances[$classname])) {
      if (class_exists($classname)) {
        $classMethods = get_class_methods($classname);

        
        if (in_array('loadJson', $classMethods, true)) {
          $fileJson = SettingsClass::getPath() . $classname . '.json';
          if (file_exists($fileJson)) {
            self::$instances[$classname] = call_user_func(array($classname, 'loadJson'), $classname);
            if (self::$instances[$classname] !== false) {
              self::$instances[$classname]->extendSettingsWithNewDefaults();

              return self::$instances[$classname];
            }
          }

          unset($fileJson);
        }

        $uri = SettingsClass::getPath() . $classname . '.php';
        if (file_exists($uri)) {
          self::$instances[$classname] = call_user_func(array($classname, 'load'), $classname);
          if (self::$instances[$classname] !== false) {
            self::$instances[$classname]->extendSettingsWithNewDefaults();
          }
        } else {
          self::$instances[$classname] = new $classname();
        }

        if (self::$instances[$classname] !== false
            && in_array('loadJson', $classMethods, true) && in_array('saveJson', $classMethods, true)) {
          self::$instances[$classname]->saveJson();
        }
      } else {
        throw new Exception('ungültige Konfigdatei: ' . $classname);
      }
    }

    return self::$instances[$classname];
  }
}