<?php

namespace CMSMSExt\ModuleFunctions;

use CMSMSExt\core\morphable;

class preferences extends morphable
{
  
  protected $_module;
  //protected $_defaults = [];
  function __construct(\CMSMSExt\XTModule  $module = null, $preferences = [], $defaults = [])
  {
    if(!$module)
    {
      throw new \RuntimeException('no module set');
    }
    
    $this->_module = $module;
    
    if( $this->_isAssoc($defaults) && $this->_isAssoc($preferences) )
    {
      $preferences = \array_merge($defaults, $preferences);
    }

    parent::__construct($preferences);
  }
  
  public function add($key, $preference) : preferences
  {
    $this->offsetSet($key, $preference);
    
    return $this;
  }
  
  public function remove($key) : preferences
  {
    $this->offsetUnset($key);
    $this->_module->RemovePreference($key);
    
    return $this;
  }
  
  /**
   * Retrieves the preference value or from the module config if either exist.
   * Otherwise, returns the default value if provided.
   *
   * @param mixed $key The key to retrieve the value for.
   * @param mixed $default The default value to return if the key is not found.
   *
   * @return mixed The value associated with the key, or the default value if the key is not found.
   */
  #[\ReturnTypeWillChange]
  public function offsetGet($key, $default = null)
  {
    $moduleConfig     = $this->_module->GetExtendedConfig();
    $modulePreference = $this->_module->GetPreference($key);
    $localValue       = parent::offsetExists($key) ? parent::offsetGet($key) : null;
    
    if(NULL !== $modulePreference && '' !== $modulePreference)
    {
      $result = $modulePreference;
    }
    else if(NULL !== $localValue && '' !== $localValue)
    {
      $result = $localValue;
    }
    else if(isset($moduleConfig[$key]) && '' !== $moduleConfig[$key])
    {
      $result = $moduleConfig[$key];
    }
    else
    {
      $result = $default;
    }
    
    return $result;
  }
  
  #[\ReturnTypeWillChange]
  public function offsetSet($key, $value) : preferences
  {
    $this->_module->SetPreference($key, $value);
    
    parent::offsetSet($key, new preference($value));

    return $this;
  }
}



?>
