<?php

/**
 * Base class for response
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is protected by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * @copyright  2014 Lifestyle Webconsulting GmbH
 * @version    $Id:$
 * @link       http://www.life-style.de
 */

namespace AppBundle\Model\Response;

use AppBundle\Api\Manager as ApiManager;
use AppBundle\Model\Base as ModelBase;
use AppBundle\Model\Request\Base as RequestBase;
use Sso\WebserviceBundle\Exception\HiddenException;

/**
 * Base class for response
 */
abstract class Base extends ModelBase
{
    /**
     * Api Manager
     * 
     * @var ApiManager
     */
    protected $apiM;

    /**
     * Constructor
     * 
     * @param ApiManager $apiM
     */
    public function __construct(ApiManager $apiM)
    {
        $this->apiM = $apiM;
    }

    /**
     * Returns response message e. g. Application added
     * 
     * @return string|bool Set to false, to suppress message element
     */
    abstract protected function getResponseMessage();

    /**
     * Returns response true, false or Success, Failure
     * 
     * @return string|bool
     */
    protected function getResponseStatus()
    {
        return true;
    }

    /**
     * Build response body
     * 
     * @param \DOMElement $xmlContainer
     */
    protected function buildResponseBody(\DOMElement $xmlContainer)
    {
        if (false !== ($message = $this->getResponseMessage())) {
            $xmlContainer->appendChild($this->apiM->responseBuilder()->document()->createTextElement('Message', $message));
        }
    }

    /**
     * Generate xml response
     * 
     * @param RequestBase $requestModel
     */
    protected function buildResponse(RequestBase $requestModel)
    {

        // An error has occured
        if ($this->apiM->errors()->hasErrors()) {
            throw new HiddenException();
        }

        $action = $this->apiM->responseBuilder()->action();
        $this->apiM->responseBuilder()->status($this->getResponseStatus());
        $this->buildResponseBody($action);
    }

}
