<?php

/**
 *
 * @class Show
 * @author sb
 *
 * 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  2015 Lifestyle Webconsulting GmbH
 * @version    $Id:$
 * @link       http://www.life-style.de
 *
 */

namespace Sso\Webservices\ObjectBundle\Model\Response\Type\Show;

use Sso\Webservices\ObjectBundle\Model\Response\Type\Base as TypeBase;
use Sso\Webservices\ObjectBundle\Entity\Type as TypeEntity;
use LifeStyle\Tools\WebserviceBundle\Error\Type\External as ExternalError;
use Sso\Webservices\ObjectBundle\Model\Response\Type\Show\Entity as ResponseType;

class Show extends TypeBase
{

    /**
     *
     * @var \DOMElement
     */
    protected $xmlContainer;

    /**
     *
     * @var ModelType[]
     */
    protected $typeEntities;

    /**
     *
     * @param TypeEntity $requestEntity
     */
    public function init($typeEntities)
    {
        //ok first set the db entity
        $this->typeEntities = $typeEntities;
    }

    /**
     * Returns response status
     *
     * @return string|bool
     */
    protected function getResponseStatus()
    {
        return $this->typeEntities ? 'Success' : 'Failure';
    }

    /**
     * Returns response message
     *
     * @return string
     */
    protected function getResponseMessage()
    {
        return $this->typeEntities ? false : 'Type not found';
    }

    /**
     * Build response body
     *
     * @param \DOMElement $xmlContainer
     */
    protected function buildResponseBody(\DOMElement $xmlContainer)
    {
        parent::buildResponseBody($xmlContainer);
        $this->xmlContainer = $xmlContainer;
        if ($this->typeEntities) {
            //now we are remap enity
            $this->apiM->responseBuilder()->addCount(count($this->typeEntities));

            foreach ($this->typeEntities as $modelIn) {
                $modelOut = new ResponseType();
                $modelOut = $this->apiM->mapper()->modelInToModelOut($modelIn, $modelOut);

                $document = $this->apiM->responseBuilder()->document();
                $docFragment = $document->createDocumentFragment();
                $docFragment->appendXML(preg_replace('/^\<?[^\>]*\>\s*/', '',
                    $this->apiM->serializer()->serialize($modelOut, 'xml')));

                $xmlContainer->appendChild($docFragment);
            }
        } else {
            $this->apiM->errors()->clearErrors();
            $this->apiM->errors()->addError(new ExternalError('ts001', 'No types found.', 'No types found.',
                'No types found for given id.'));
        }
    }

}
