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


class ErrorMessageAPI
{
  
  private $errorCode;
  
  private $errorMessage;
  
  private $webid;
  private $fields;       
  
  private $undeletedNewsIds;

  const ERROR_NO_ERROR = 0; 
  const ERROR_GENERIC_ERROR = 21000; 
  const ERROR_INVALID_LOGIN = 21001; 
  const ERROR_NO_INPUT = 21002;
  const ERROR_FILTER_PROBLEM = 21003; 
  const ERROR_DEL_NOT_SUCCESSFUL = 21004; 

  
  public function __construct($errCode, $errMsg = null, $pWebId = '')
  {
    $this->errorCode = $errCode;
    $this->errorMessage = $errMsg;
    $this->webid = $pWebId;
    $this->undeletedNewsIds = array();
  }

  
  public function setFields($fields)
  {
    if (is_array($fields)) {
      $this->fields = $fields;
    }
  }

  
  public function setUndeletedNewsIds($pNewsIds)
  {
    if ($pNewsIds === '') {
      return;
    }
    if (is_array($pNewsIds)) {
      $this->undeletedNewsIds = $pNewsIds;
    } else {
      $this->undeletedNewsIds[] = $pNewsIds;
    }
  }

  
  public function getXML()
  {
    $node = $this->getXMLNode();

    return $node->getXMLstring();
  }

  
  private function getXMLNode()
  {
    $rootNode = new XMLNode('error');

    $rootNode->addChild(new XMLNode('errorcode', $this->errorCode));

    if ($this->errorMessage !== null && trim($this->errorMessage) !== '') {
      $rootNode->addChild(new XMLNode('errormessage', $this->errorMessage));
    }

    if ($this->fields !== null && $this->fields !== array()) {
      $fieldsNode = new XMLNode('fields');
      foreach ($this->fields as $name => $content) {
        $fieldNode = new XMLNode('field', '', "name=\"{$name}\"");
        foreach ($content as $key => $val) {
          $fieldNode->addChild(new XMLNode($key, $val));
        }
        $fieldsNode->addChild($fieldNode);
      }
      $rootNode->addChild($fieldsNode);
    }

    if ($this->webid != '') {
      $rootNode->addChild(new XMLNode('webid', $this->webid));
    }

    if (is_array($this->undeletedNewsIds) && count($this->undeletedNewsIds) > 0) {
      $rootNode->addChild(new XMLNode('undeletedIds', implode(',', $this->undeletedNewsIds)));
    }

    return $rootNode;
  }
}