<?php


namespace CMSMSExt\Exceptions;


class Exception extends \Exception
{
  
  private $_mod;
  
  /**
   * Exception constructor.
   *
   * A mixed number and type of parameters can be passed
   * to the constructor to add support for error localization
   * where required
   *
   * For localization (use of the module's lang strings)
   * it is required that the very 1st parameter passed
   * is the module itself
   *
   *
   */
  public function __construct()
  {
  
    $params     = \func_get_args();
    $tmp_params = [];
    $newparams  = [];
    
    if(\count($params) && $params[0] instanceof \CMSModule)
    {
      $this->_mod = $params[0];
      unset($params[0]);
      $params = \array_values($params);
    }
    
    if( !isset($params[0]) )
    {
      $code = \CMSMSExt\core\Error::UNKNOWN;
      
      # we need it twice: once for the Lang string translation and one to display the error code itself
      $newparams[] = $newparams[] = $code;
    }
    else
    {
      # a numeric code has been provided instead of a message
      if( \is_numeric($params[0]) )
      {
        $code = $params[0];
        # separate additional $params
        $tmp_params = \array_slice($params, 1);
        $newparams[] = $newparams[] = $code;
      }
      else if( 1 === \count($params) )
        # this is just a custom message instead of a  error code: GENERIC
      {
        $code = \CMSMSExt\core\Error::GENERIC;
        $newparams[] = $newparams[] = $code;
        $newparams[] = $params[0];
      }
      else
        # the call has been called with all its parameters filled:
        # i.e.: throw new CMSMSExt\Exceptions\Exception($msg, $code[, $param1][, $param2]...[, $param(n)])
        # where the extra params are passed to the <Module>->Lang() method as additional params
      {
        $code = $params[1];
        # separate additional $params
        $tmp_params = \array_slice($params, 2);
        $newparams[] = $newparams[] = $code;
        $newparams[] = $params[0];
      }
      
      # prevent non existing errors
      if( !\CMSMSExt\core\Error::HasCode($code) )
      {
        $code = \CMSMSExt\core\Error::UNKNOWN;
        $newparams[] = $newparams[] = $code;
      }
    }
  
    # we merge any additional params
    $newparams = \array_merge($newparams, $tmp_params);
    
    if(NULL === $this->_mod)
    {
      # so we don't have a module to pass it on to it's Lang method
      $msg = (string)$params[0];
    }
    else
    {
      # pass merged parameters to the module->Lang();
      $msg = \call_user_func_array([$this->_mod, 'Lang'], $newparams);
    }
    
    parent::__construct($msg, (int)$code);
  }
  
  public function __toString()
  {
    return '## ' . $this->message . ' ##';
  }
}

?>